Coder Social home page Coder Social logo

brendonovich / prisma-client-rust Goto Github PK

View Code? Open in Web Editor NEW
1.8K 14.0 104.0 1.99 MB

Type-safe database access for Rust

Home Page: https://prisma.brendonovich.dev

License: Apache License 2.0

Rust 100.00%
prisma prisma-client prisma-client-rust rust

prisma-client-rust's Issues

m-m relations break generation

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "cargo prisma"
  output   = "../src/prisma.rs"
}

model Post {
  id          String     @id @default(auto()) @map("_id") @db.ObjectId
  categoryIDs String[]   @db.ObjectId
  categories  Category[] @relation(fields: [categoryIDs], references: [id])
}

model Category {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId
  postIDs String[] @db.ObjectId
  posts   Post[]   @relation(fields: [postIDs], references: [id])
}

Generate the client, try to compile and there will be errors.

TableDoesNotExist error

Hi, I run my project with simple code, but there is some error that I can't solve, can you help me?

here is my error log

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: InterpreterError(ConnectorError(ConnectorError { user_facing_error: Some(KnownError { message: "The table `main.User` does not exist in the current database.", meta: Object({"table": String("main.User")}), error_code: "P2021" }), kind: TableDoesNotExist { table: "main.User" } }))', ~/.cargo/git/checkouts/prisma-client-rust-fa967aa5ad0ec391/0f29315/src/query.rs:77:14

this is the link that can reproduce this error in my computer.
https://github.com/ltaoo/prisma-client-rust-bug

here is my system info

  System:
    OS: macOS 12.2.1
    CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
    Memory: 1.05 GB / 8.00 GB
    Shell: 5.8 - /bin/zsh
rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.60.0 (7737e0b5c 2022-04-04)`
rustc 1.60.0 (7737e0b5c 2022-04-04)
cargo 1.60.0 (d1fd9fe2c 2022-03-01)

Problems with big schema

Hey, I have a schema that was generated by db introspection, which seems to cause several issues.
I've added @@ignore to all of them for now, so that I can continue with my work.

The schema:

model directus_activity {
  id                 Int                  @id @default(autoincrement())
  action             String               @db.VarChar(45)
  user               String?              @db.Uuid
  timestamp          DateTime             @default(now()) @db.Timestamptz(6)
  ip                 String               @db.VarChar(50)
  user_agent         String?              @db.VarChar(255)
  collection         String               @db.VarChar(64)
  item               String               @db.VarChar(255)
  comment            String?
  directus_revisions directus_revisions[]

  @@ignore
}

model directus_collections {
  collection                 String                 @id @db.VarChar(64)
  icon                       String?                @db.VarChar(30)
  note                       String?
  display_template           String?                @db.VarChar(255)
  hidden                     Boolean                @default(false)
  singleton                  Boolean                @default(false)
  translations               Json?                  @db.Json
  archive_field              String?                @db.VarChar(64)
  archive_app_filter         Boolean                @default(true)
  archive_value              String?                @db.VarChar(255)
  unarchive_value            String?                @db.VarChar(255)
  sort_field                 String?                @db.VarChar(64)
  accountability             String?                @default("all") @db.VarChar(255)
  color                      String?                @db.VarChar(255)
  item_duplication_fields    Json?                  @db.Json
  sort                       Int?
  group                      String?                @db.VarChar(64)
  collapse                   String                 @default("open") @db.VarChar(255)
  directus_collections       directus_collections?  @relation("directus_collectionsTodirectus_collections_group", fields: [group], references: [collection], onDelete: NoAction, onUpdate: NoAction, map: "directus_collections_group_foreign")
  other_directus_collections directus_collections[] @relation("directus_collectionsTodirectus_collections_group")
  directus_shares            directus_shares[]

  @@ignore
}

model directus_dashboards {
  id              String            @id @db.Uuid
  name            String            @db.VarChar(255)
  icon            String            @default("dashboard") @db.VarChar(30)
  note            String?
  date_created    DateTime?         @default(now()) @db.Timestamptz(6)
  user_created    String?           @db.Uuid
  directus_users  directus_users?   @relation(fields: [user_created], references: [id], onUpdate: NoAction, map: "directus_dashboards_user_created_foreign")
  directus_panels directus_panels[]

  @@ignore
}

model directus_fields {
  id                 Int      @id @default(autoincrement())
  collection         String   @db.VarChar(64)
  field              String   @db.VarChar(64)
  special            String?  @db.VarChar(64)
  interface          String?  @db.VarChar(64)
  options            Json?    @db.Json
  display            String?  @db.VarChar(64)
  display_options    Json?    @db.Json
  readonly           Boolean  @default(false)
  hidden             Boolean  @default(false)
  sort               Int?
  width              String?  @default("full") @db.VarChar(30)
  translations       Json?    @db.Json
  note               String?
  conditions         Json?    @db.Json
  required           Boolean? @default(false)
  group              String?  @db.VarChar(64)
  validation         Json?    @db.Json
  validation_message String?

  @@ignore
}

model directus_files {
  id                                                                    String              @id @db.Uuid
  storage                                                               String              @db.VarChar(255)
  filename_disk                                                         String?             @db.VarChar(255)
  filename_download                                                     String              @db.VarChar(255)
  title                                                                 String?             @db.VarChar(255)
  type                                                                  String?             @db.VarChar(255)
  folder                                                                String?             @db.Uuid
  uploaded_by                                                           String?             @db.Uuid
  uploaded_on                                                           DateTime            @default(now()) @db.Timestamptz(6)
  modified_by                                                           String?             @db.Uuid
  modified_on                                                           DateTime            @default(now()) @db.Timestamptz(6)
  charset                                                               String?             @db.VarChar(50)
  filesize                                                              BigInt?
  width                                                                 Int?
  height                                                                Int?
  duration                                                              Int?
  embed                                                                 String?             @db.VarChar(200)
  description                                                           String?
  location                                                              String?
  tags                                                                  String?
  metadata                                                              Json?               @db.Json
  directus_folders                                                      directus_folders?   @relation(fields: [folder], references: [id], onUpdate: NoAction, map: "directus_files_folder_foreign")
  directus_users_directus_files_modified_byTodirectus_users             directus_users?     @relation("directus_files_modified_byTodirectus_users", fields: [modified_by], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_files_modified_by_foreign")
  directus_users_directus_files_uploaded_byTodirectus_users             directus_users?     @relation("directus_files_uploaded_byTodirectus_users", fields: [uploaded_by], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_files_uploaded_by_foreign")
  directus_settings_directus_filesTodirectus_settings_project_logo      directus_settings[] @relation("directus_filesTodirectus_settings_project_logo")
  directus_settings_directus_filesTodirectus_settings_public_background directus_settings[] @relation("directus_filesTodirectus_settings_public_background")
  directus_settings_directus_filesTodirectus_settings_public_foreground directus_settings[] @relation("directus_filesTodirectus_settings_public_foreground")

  @@ignore
}

model directus_folders {
  id                     String              @id @db.Uuid
  name                   String              @db.VarChar(255)
  parent                 String?             @db.Uuid
  directus_folders       directus_folders?   @relation("directus_foldersTodirectus_folders_parent", fields: [parent], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_folders_parent_foreign")
  directus_files         directus_files[]
  other_directus_folders directus_folders[]  @relation("directus_foldersTodirectus_folders_parent")
  directus_settings      directus_settings[]

  @@ignore
}

model directus_migrations {
  version   String    @id @db.VarChar(255)
  name      String    @db.VarChar(255)
  timestamp DateTime? @default(now()) @db.Timestamptz(6)

  @@ignore
}

model directus_notifications {
  id                                                              Int            @id @default(autoincrement())
  timestamp                                                       DateTime       @db.Timestamptz(6)
  status                                                          String?        @default("inbox") @db.VarChar(255)
  recipient                                                       String         @db.Uuid
  sender                                                          String         @db.Uuid
  subject                                                         String         @db.VarChar(255)
  message                                                         String?
  collection                                                      String?        @db.VarChar(64)
  item                                                            String?        @db.VarChar(255)
  directus_users_directus_notifications_recipientTodirectus_users directus_users @relation("directus_notifications_recipientTodirectus_users", fields: [recipient], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_notifications_recipient_foreign")
  directus_users_directus_notifications_senderTodirectus_users    directus_users @relation("directus_notifications_senderTodirectus_users", fields: [sender], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_notifications_sender_foreign")

  @@ignore
}

model directus_panels {
  id                  String              @id @db.Uuid
  dashboard           String              @db.Uuid
  name                String?             @db.VarChar(255)
  icon                String?             @db.VarChar(30)
  color               String?             @db.VarChar(10)
  show_header         Boolean             @default(false)
  note                String?
  type                String              @db.VarChar(255)
  position_x          Int
  position_y          Int
  width               Int
  height              Int
  options             Json?               @db.Json
  date_created        DateTime?           @default(now()) @db.Timestamptz(6)
  user_created        String?             @db.Uuid
  directus_dashboards directus_dashboards @relation(fields: [dashboard], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_panels_dashboard_foreign")
  directus_users      directus_users?     @relation(fields: [user_created], references: [id], onUpdate: NoAction, map: "directus_panels_user_created_foreign")

  @@ignore
}

model directus_permissions {
  id             Int             @id @default(autoincrement())
  role           String?         @db.Uuid
  collection     String          @db.VarChar(64)
  action         String          @db.VarChar(10)
  permissions    Json?           @db.Json
  validation     Json?           @db.Json
  presets        Json?           @db.Json
  fields         String?
  directus_roles directus_roles? @relation(fields: [role], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_permissions_role_foreign")

  @@ignore
}

model directus_presets {
  id               Int             @id @default(autoincrement())
  bookmark         String?         @db.VarChar(255)
  user             String?         @db.Uuid
  role             String?         @db.Uuid
  collection       String?         @db.VarChar(64)
  search           String?         @db.VarChar(100)
  layout           String?         @default("tabular") @db.VarChar(100)
  layout_query     Json?           @db.Json
  layout_options   Json?           @db.Json
  refresh_interval Int?
  filter           Json?           @db.Json
  icon             String          @default("bookmark_outline") @db.VarChar(30)
  color            String?         @db.VarChar(255)
  directus_roles   directus_roles? @relation(fields: [role], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_presets_role_foreign")
  directus_users   directus_users? @relation(fields: [user], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_presets_user_foreign")

  @@ignore
}

model directus_relations {
  id                      Int     @id @default(autoincrement())
  many_collection         String  @db.VarChar(64)
  many_field              String  @db.VarChar(64)
  one_collection          String? @db.VarChar(64)
  one_field               String? @db.VarChar(64)
  one_collection_field    String? @db.VarChar(64)
  one_allowed_collections String?
  junction_field          String? @db.VarChar(64)
  sort_field              String? @db.VarChar(64)
  one_deselect_action     String  @default("nullify") @db.VarChar(255)

  @@ignore
}

model directus_revisions {
  id                       Int                  @id @default(autoincrement())
  activity                 Int
  collection               String               @db.VarChar(64)
  item                     String               @db.VarChar(255)
  data                     Json?                @db.Json
  delta                    Json?                @db.Json
  parent                   Int?
  directus_activity        directus_activity    @relation(fields: [activity], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_revisions_activity_foreign")
  directus_revisions       directus_revisions?  @relation("directus_revisionsTodirectus_revisions_parent", fields: [parent], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_revisions_parent_foreign")
  other_directus_revisions directus_revisions[] @relation("directus_revisionsTodirectus_revisions_parent")

  @@ignore
}

model directus_roles {
  id                   String                 @id @db.Uuid
  name                 String                 @db.VarChar(100)
  icon                 String                 @default("supervised_user_circle") @db.VarChar(30)
  description          String?
  ip_access            String?
  enforce_tfa          Boolean                @default(false)
  admin_access         Boolean                @default(false)
  app_access           Boolean                @default(true)
  directus_permissions directus_permissions[]
  directus_presets     directus_presets[]
  directus_shares      directus_shares[]
  directus_users       directus_users[]

  @@ignore
}

model directus_sessions {
  token           String           @id @db.VarChar(64)
  user            String?          @db.Uuid
  expires         DateTime         @db.Timestamptz(6)
  ip              String?          @db.VarChar(255)
  user_agent      String?          @db.VarChar(255)
  share           String?          @db.Uuid
  directus_shares directus_shares? @relation(fields: [share], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_sessions_share_foreign")
  directus_users  directus_users?  @relation(fields: [user], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_sessions_user_foreign")

  @@ignore
}

model directus_settings {
  id                                                                 Int               @id @default(autoincrement())
  project_name                                                       String            @default("Directus") @db.VarChar(100)
  project_url                                                        String?           @db.VarChar(255)
  project_color                                                      String?           @db.VarChar(50)
  project_logo                                                       String?           @db.Uuid
  public_foreground                                                  String?           @db.Uuid
  public_background                                                  String?           @db.Uuid
  public_note                                                        String?
  auth_login_attempts                                                Int?              @default(25)
  auth_password_policy                                               String?           @db.VarChar(100)
  storage_asset_transform                                            String?           @default("all") @db.VarChar(7)
  storage_asset_presets                                              Json?             @db.Json
  custom_css                                                         String?
  storage_default_folder                                             String?           @db.Uuid
  basemaps                                                           Json?             @db.Json
  mapbox_key                                                         String?           @db.VarChar(255)
  module_bar                                                         Json?             @db.Json
  project_descriptor                                                 String?           @db.VarChar(100)
  translation_strings                                                Json?             @db.Json
  default_language                                                   String            @default("en-US") @db.VarChar(255)
  directus_files_directus_filesTodirectus_settings_project_logo      directus_files?   @relation("directus_filesTodirectus_settings_project_logo", fields: [project_logo], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_settings_project_logo_foreign")
  directus_files_directus_filesTodirectus_settings_public_background directus_files?   @relation("directus_filesTodirectus_settings_public_background", fields: [public_background], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_settings_public_background_foreign")
  directus_files_directus_filesTodirectus_settings_public_foreground directus_files?   @relation("directus_filesTodirectus_settings_public_foreground", fields: [public_foreground], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "directus_settings_public_foreground_foreign")
  directus_folders                                                   directus_folders? @relation(fields: [storage_default_folder], references: [id], onUpdate: NoAction, map: "directus_settings_storage_default_folder_foreign")

  @@ignore
}

model directus_shares {
  id                   String                @id @db.Uuid
  name                 String?               @db.VarChar(255)
  collection           String?               @db.VarChar(64)
  item                 String?               @db.VarChar(255)
  role                 String?               @db.Uuid
  password             String?               @db.VarChar(255)
  user_created         String?               @db.Uuid
  date_created         DateTime?             @default(now()) @db.Timestamptz(6)
  date_start           DateTime?             @db.Timestamptz(6)
  date_end             DateTime?             @db.Timestamptz(6)
  times_used           Int?                  @default(0)
  max_uses             Int?
  directus_collections directus_collections? @relation(fields: [collection], references: [collection], onDelete: Cascade, onUpdate: NoAction, map: "directus_shares_collection_foreign")
  directus_roles       directus_roles?       @relation(fields: [role], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "directus_shares_role_foreign")
  directus_users       directus_users?       @relation(fields: [user_created], references: [id], onUpdate: NoAction, map: "directus_shares_user_created_foreign")
  directus_sessions    directus_sessions[]

  @@ignore
}

model directus_users {
  id                                                                      String                   @id @db.Uuid
  first_name                                                              String?                  @db.VarChar(50)
  last_name                                                               String?                  @db.VarChar(50)
  email                                                                   String?                  @unique(map: "directus_users_email_unique") @db.VarChar(128)
  password                                                                String?                  @db.VarChar(255)
  location                                                                String?                  @db.VarChar(255)
  title                                                                   String?                  @db.VarChar(50)
  description                                                             String?
  tags                                                                    Json?                    @db.Json
  avatar                                                                  String?                  @db.Uuid
  language                                                                String?                  @db.VarChar(255)
  theme                                                                   String?                  @default("auto") @db.VarChar(20)
  tfa_secret                                                              String?                  @db.VarChar(255)
  status                                                                  String                   @default("active") @db.VarChar(16)
  role                                                                    String?                  @db.Uuid
  token                                                                   String?                  @unique(map: "directus_users_token_unique") @db.VarChar(255)
  last_access                                                             DateTime?                @db.Timestamptz(6)
  last_page                                                               String?                  @db.VarChar(255)
  provider                                                                String                   @default("default") @db.VarChar(128)
  external_identifier                                                     String?                  @unique(map: "directus_users_external_identifier_unique") @db.VarChar(255)
  auth_data                                                               Json?                    @db.Json
  email_notifications                                                     Boolean?                 @default(true)
  directus_roles                                                          directus_roles?          @relation(fields: [role], references: [id], onUpdate: NoAction, map: "directus_users_role_foreign")
  directus_dashboards                                                     directus_dashboards[]
  directus_files_directus_files_modified_byTodirectus_users               directus_files[]         @relation("directus_files_modified_byTodirectus_users")
  directus_files_directus_files_uploaded_byTodirectus_users               directus_files[]         @relation("directus_files_uploaded_byTodirectus_users")
  directus_notifications_directus_notifications_recipientTodirectus_users directus_notifications[] @relation("directus_notifications_recipientTodirectus_users")
  directus_notifications_directus_notifications_senderTodirectus_users    directus_notifications[] @relation("directus_notifications_senderTodirectus_users")
  directus_panels                                                         directus_panels[]
  directus_presets                                                        directus_presets[]
  directus_sessions                                                       directus_sessions[]
  directus_shares                                                         directus_shares[]

  @@ignore
}

model directus_webhooks {
  id          Int     @id @default(autoincrement())
  name        String  @db.VarChar(255)
  method      String  @default("POST") @db.VarChar(10)
  url         String  @db.VarChar(255)
  status      String  @default("active") @db.VarChar(10)
  data        Boolean @default(true)
  actions     String  @db.VarChar(100)
  collections String  @db.VarChar(255)
  headers     Json?   @db.Json

  @@ignore
}

Enums incorrectly treated as GraphQL types

I'm getting a bug when running generate:

{"jsonrpc":"2.0","id":1,"result":{"manifest":{"defaultOutput":"prisma.rs","denylist":null,"prettyName":"Prisma Client Rust","requiresEngines":null,"requiresGenerators":null}}}
thread 'main' panicked at 'Unsupported type: Role', /Users/user/.cargo/git/checkouts/prisma-client-rust-fa967aa5ad0ec391/72326a9/cli/src/generator/types.rs:128:18
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

My schema is pretty simple and yet I can't get around this.

// ...
model User {
  id   String @id @default(cuid())
  role UserRole
}

enum UserRole {
  ADMIN
  USER
}

What did I miss? Is this a bug? What am I doing wrong?

Unique multi-column constraint

Hey, I'm not sure if this behaviour is intended, but it seems quite cumbersome to me.

Let's say we have the schema:

model Category {
  id       Int       @id @default(autoincrement())
  name     String
  parent   Category? @relation("CategoryChildren", fields: [parentId], references: [id])
  parentId Int?

  children Category[]             @relation("CategoryChildren")
  programs CategoriesOnPrograms[]

  @@unique([name, parentId])
}

The generated UniqueParams are:

    pub enum UniqueWhereParam {
        NameParentIdEquals(String, i32),
        IdEquals(i32),
    }

But shouldn't it be the following, since the parent is optional?:

    pub enum UniqueWhereParam {
        NameParentIdEquals(String,Option<i32>),
        IdEquals(i32),
    }

Empty UniqueWhereParam enum

Hi, first of all thanks for this crate!

When updating to the latest commit (31a864a) I found that the generated UniqueWhereParam had no variants anymore...

model to reproduce:

model Post {
  userId    String
  projectId String
  content   String
  @@id([userId, projectId, content])
}

With commit 94bef1d the generated UniqueWhereParam enum looks like this:

    pub enum UniqueWhereParam {
        UserIdProjectIdContentEquals(String, String, String),
    }

after that commit an empty enum is generated:

    pub enum UniqueWhereParam {}

Best regards

Nested operations

With, fetch and update are implemented for non-nested actions, but going any deeper than that isn't currently possible.
Supporting this isn't hard, just takes more codegen and some more thought.

Nested queries

Nested With/Fetch Example

client
    .user()
    .find_unique(user::id::equals(0))
    .with(user::profile::fetch()
        .with(profile::image::fetch())
    )
    .exec()
    .await;

Error handling

What's an async library without Result everywhere ๐Ÿ™ƒ

discord server

ehh this is totally not the right place for something like this, sorry in advance, but i have no idea how else i could ask this.

I think a discord server would be useful for general questions and stuff, like simple help.

Enum defined twice if `@id` is also marked with `@unique`

   Compiling glowsquid v0.1.0 (/mnt/BulkStorage/projects/github.com/glowsquid-launcher/glowsquid/apps/oxidize)
error[E0428]: the name `IdEquals` is defined multiple times
   --> src/prisma.rs:875:5
    |
873 |     IdEquals(String),
    |     ---------------- previous definition of the type `IdEquals` here
874 |     UsernameEquals(String),
875 |     IdEquals(String),
    |     ^^^^^^^^^^^^^^^^ `IdEquals` redefined here
    |
    = note: `IdEquals` must be defined only once in the type namespace of this enum

For more information about this error, try `rustc --explain E0428`.
error: could not compile `glowsquid` due to previous error

[Process exited 0]

schema:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "cargo prisma"
  output   = "../src/prisma.rs"
}

datasource db {
  provider = "sqlite"
  url      = "file:dev.db"
}

/// A minecraft account
model Account {
  /// The account's unique id
  id            String   @id @unique // <-- issue is here
  /// The account's username
  username      String   @unique

}

Async CLI output

When installing and running the CLI on Windows, the following happens to me:

C:\Users\Jan\Documents\throwaway\  ([email protected])
ฮป prisma-client-rust --help

C:\Users\Jan\Documents\throwaway\  ([email protected])
ฮป
Prisma is a modern DB toolkit to query, migrate and model your database (https://prisma.io)

Usage

  $ prisma [command]

Commands

            init   Setup Prisma for your app
        generate   Generate artifacts (e.g. Prisma Client)
              db   Manage your database schema and lifecycle
         migrate   Migrate your database
          studio   Browse your data with Prisma Studio
          format   Format your schema

Flags

     --preview-feature   Run Preview Prisma commands

Examples

  Setup a new Prisma project
  $ prisma init

  Generate artifacts (e.g. Prisma Client)
  $ prisma generate

  Browse your data
  $ prisma studio

  Create migrations from your Prisma schema, apply them to the database, generate artifacts (e.g. Prisma Client)
  $ prisma migrate dev

  Pull the schema from an existing database, updating the Prisma schema
  $ prisma db pull

  Push the Prisma schema state to the database
  $ prisma db push

Note how the CLI already shows the prompt again before the output happened.

CLI incompatible with rust version < 1.58

Compiling serde v1.0.136
Compiling mysql_common v0.28.2
Compiling futures-executor v0.3.21
Compiling tokio-util v0.6.9
Compiling tokio-util v0.7.1
Compiling tokio-native-tls v0.3.0 (https://github.com/pimeys/tls?branch=vendored-openssl#6d0e6fc7)
Compiling asynchronous-codec v0.5.0
Compiling async-native-tls v0.4.0
Compiling mobc v0.7.3 (https://github.com/prisma/mobc?tag=1.0.0#75c68f10)
Compiling trust-dns-proto v0.20.4
Compiling tokio-rustls v0.22.0
Compiling schema-ast v0.1.0 (https://github.com/Brendonovich/prisma-engines?rev=8c1da2fdc058b7af8905a61491856cade06f952f#8c1da2fd)
error: there is no argument named name
--> C:\Users\xxx.cargo\git\checkouts\prisma-engines-8e1416dd0e571d11\8c1da2f\libs\datamodel\schema-ast\src\parser\parse_composite_type.rs:78:49
|
78 | ... "Defining @{name} attribute for a field in a composite type is not allowed."
| ^^^^^^

Compiling futures v0.3.21
Compiling opentelemetry v0.16.0
error: could not compile schema-ast due to previous error
warning: build failed, waiting for other jobs to finish...
error: build failed

Warn user if CLI version and runtime version don't match

The code generated by the CLI may rely on stuff exported from the prisma-client-rust library which is added to the individual projects which use this library. A compiler error should be thrown if the code generated by the CLI expected a higher version of the prisma-client-rust dependency in the specific project, to prompt the developer to update it.

Float type not compiling properly, missing crate?

This issue is kinda split into two

  1. Float seems to be using a external crate, this possibly needs to be documented as its not included with the crate
  2. Even with the crate it seems that from_f64 is not working, is it meant to be this one? Here
                Self::ChanceNot(value) => (
                    "chance".to_string(),
                    SerializedWhereValue::Object(vec![(
                        "not".to_string(),
                        PrismaValue::Float(bigdecimal::from_f64(value).unwrap().normalized()) // <-- This bigdecimal
                            .into(),
                    )]),
                ),

Nested create

The following should be possible:

client
    .user()
    .create(
        "Name".to_string(),
        user::image::create("some url".to_string(), vec![]),
    )
    .exec()
    .await;

Compilation errors

schema:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "cargo prisma"
  output   = "../src/prisma.rs"
}

datasource db {
  provider = "sqlite"
  url      = "file:dev.db"
}

/// A minecraft account
model Account {
  /// The account's unique id
  id            String   @id
  /// The account's username
  username      String   @unique
  /// The account's access token. To be refreshed when expired
  accessToken   String
  /// The account's refresh token. To be used to refresh the access token
  refreshToken  String
  /// The time the access token expires. If this is in the past, the access token needs to be refreshed
  expiresAt     DateTime
  /// The last time the access token was refreshed
  lastRefreshed DateTime @updatedAt
}

/// A modpack
model Modpack {
  /// The modpack's id.
  modpackId         String
  /// The adapter associated with this modpack.
  adapter           String
  /// The modpack's name.
  name              String
  /// The path on the filesystem to the modpack's root directory.
  path              String
  /// The modpack's version.
  version           String
  /// URL to the icon for this modpack.
  iconUrl           String
  /// The modpack's description. Can be HTML or Markdown
  description       String
  /// The modpack's description format.
  descriptionFormat String
  /// A short description of the modpack in plaintext
  shortDescription  String
  /// The modpack's author.
  author            String
  mods              ModsInModpack[]

  @@id([modpackId, adapter])
}

model Mod {
  /// The mod's id.
  modId             String          @map("modid")
  /// The mod's adapter
  adapter           String
  /// The mod's name.
  name              String
  /// The mod's version. Should be semver compliant.
  version           String
  /// The name of the mod file that is in the cache
  file              String
  /// The mod's description. Can be HTML or Markdown
  description       String
  /// The mod's description format.
  descriptionFormat String
  /// A short description of the mod in plaintext
  shortDescription  String
  /// The mod's author.
  author            String
  /// The modpacks this mod is in
  modpack           ModsInModpack[]

  @@id([modId, adapter])
}

model ModsInModpack {
  mod        Mod    @relation(fields: [modId, modAdapter], references: [modId, adapter])
  modId      String
  modAdapter String

  Modpack        Modpack @relation(fields: [modpackId, modpackAdapter], references: [modpackId, adapter])
  modpackId      String
  modpackAdapter String

  @@id([modpackId, modId])
}

generate client
too many compilation errors

image

QueryGraph output being logged

    Selection {
        name: "createOneUser",
        alias: Some(
            "result",
        ),
        arguments: [
            (
                "data",
                Object(
                    {
                        "username": String(
                            "asd",
                        ),
                        "email": String(
                            "asd",
                        ),
                        "password": String(
                            "$argon2id$v=19$m=4096,t=3,p=1$VrRZ0Uw9wMozofnqHjeX6g$4TP1J30u7zhzwnhDEWH8nO6AEXdNzSwok06AKDYiRn4",
                        ),
                    },
                ),
            ),
        ],
        nested_selections: [
            Selection {
                name: "id",
                alias: None,
                arguments: [],
                nested_selections: [],
            },
            Selection {
                name: "username",
                alias: None,
                arguments: [],
                nested_selections: [],
            },
            Selection {
                name: "email",
                alias: None,
                arguments: [],
                nested_selections: [],
            },
            Selection {
                name: "password",
                alias: None,
                arguments: [],
                nested_selections: [],
            },
        ],
    },
)
execute_self_contained; trace_id=None
execute; self=QueryPipeline { graph: QueryGraph { graph: "InnerGraph", result_nodes: [NodeIndex(1)], marked_node_pairs: [], finalized: true, needs_transaction: true, visited: [] }, interpreter: QueryInterpreter, serializer: IrSerializer { key: "result", output_field: OutputField { name: "createOneUser", field_type: Object((Weak)), deprecation: None, arguments: [InputField { name: "data", default_value: None, deprecation: None, field_types: [Object(UserCreateInput), Object(UserUncheckedCreateInput)], is_required: true }], is_nullable: false, query_info: Some(QueryInfo { model: Some(Model { name: "User", manifestation: Some("users"), fields: OnceCell(Fields { all: [Scalar(ScalarField { name: "id", type_identifier: String, is_id: true, is_auto_generated_int_id: false, is_autoincrement: false, internal_enum: None, is_updated_at: false, arity: Required, db_name: Some("_id"), default_value: Some(DefaultValue::Expression(auto()[])), model: "#ModelWeakRef#", is_unique: false, read_only: OnceCell(false) }), Scalar(ScalarField { name: "username", type_identifier: String, is_id: false, is_auto_generated_int_id: false, is_autoincrement: false, internal_enum: None, is_updated_at: false, arity: Required, db_name: None, default_value: None, model: "#ModelWeakRef#", is_unique: false, read_only: OnceCell(false) }), Scalar(ScalarField { name: "email", type_identifier: String, is_id: false, is_auto_generated_int_id: false, is_autoincrement: false, internal_enum: None, is_updated_at: false, arity: Required, db_name: None, default_value: None, model: "#ModelWeakRef#", is_unique: false, read_only: OnceCell(false) }), Scalar(ScalarField { name: "password", type_identifier: String, is_id: false, is_auto_generated_int_id: false, is_autoincrement: false, internal_enum: None, is_updated_at: false, arity: Required, db_name: None, default_value: None, model: "#ModelWeakRef#", is_unique: false, read_only: OnceCell(false) })], primary_key: Some(PrimaryKey { alias: None, fields: [(Weak)] }), scalar: OnceCell([(Weak), (Weak), (Weak), (Weak)]), relation: OnceCell([]), composite: OnceCell(Uninit), model: (Weak), updated_at: OnceCell(None) }), indexes: OnceCell([]), primary_identifier: OnceCell(FieldSelection { selections: [Scalar(ScalarField { name: "id", type_identifier: String, is_id: true, is_auto_generated_int_id: false, is_autoincrement: false, internal_enum: None, is_updated_at: false, arity: Required, db_name: Some("_id"), default_value: Some(DefaultValue::Expression(auto()[])), model: "#ModelWeakRef#", is_unique: false, read_only: OnceCell(false) })] }), dml_model: Model { name: "User", fields: [ScalarField(ScalarField { name: "id", field_type: Scalar(String, None, Some(NativeTypeInstance { name: "ObjectId", args: [], serialized_native_type: String("ObjectId") })), arity: Required, database_name: Some("_id"), default_value: Some(DefaultValue::Expression(auto()[])), documentation: None, is_generated: false, is_updated_at: false, is_commented_out: false, is_ignored: false }), ScalarField(ScalarField { name: "username", field_type: Scalar(String, None, None), arity: Required, database_name: None, default_value: None, documentation: None, is_generated: false, is_updated_at: false, is_commented_out: false, is_ignored: false }), ScalarField(ScalarField { name: "email", field_type: Scalar(String, None, None), arity: Required, database_name: None, default_value: None, documentation: None, is_generated: false, is_updated_at: false, is_commented_out: false, is_ignored: false }), ScalarField(ScalarField { name: "password", field_type: Scalar(String, None, None), arity: Required, database_name: None, default_value: None, documentation: None, is_generated: false, is_updated_at: false, is_commented_out: false, is_ignored: false })], documentation: None, database_name: Some("users"), indices: [], primary_key: Some(PrimaryKeyDefinition { name: None, db_name: None, fields: [PrimaryKeyField { name: "id", sort_order: None, length: None }], defined_on_field: true }), is_generated: false, is_commented_out: false, is_ignored: false }, internal_data_model: "#InternalDataModelWeakRef#" }), tag: CreateOne }) } } }

How do I stop this output from happening?

OpenSSL 3 support

From this issue

@ckgt Prisma hasn't supported OpenSSL 3 until the recent release of Prisma 1.13.0. I've updated the engine CLI versions in the latest commit, change tag = "0.4.1" to rev = "b3c93e9eced80e259578e9a916531940c3876ad5" to use the latest engines.

Nicer errors

Prisma provides UserFacingErrors or something that have nice messages and are the same as those used in the JS and Go clients. These should probably be used too.

error: non-exhaustive patterns: PollClosed { } not covered

following the configuration example the rust module is generated successfully as in the db.rs example. But when testing the queries the error happens.
any idea what could cause this?

 Compiling sql-query-connector v0.1.0 (https://github.com/prisma/prisma-engines?tag=3.10.0#73e60b76)
error[E0004]: non-exhaustive patterns: `PoolClosed {  }` not covered
   --> /home/fernandomarca/.cargo/git/checkouts/prisma-engines-c59f93cf38470c49/73e60b7/query-engine/connectors/sql-query-connector/src/error.rs:257:15
    |
257 |         match QuaintKind::from(e) {
    |               ^^^^^^^^^^^^^^^^^^^ pattern `PoolClosed {  }` not covered
    |
   ::: /home/fernandomarca/.cargo/git/checkouts/quaint-9f01e008b9a89c14/479e08a/src/error.rs:220:5
    |
220 |     PoolClosed {},
    |     ---------- not covered
    |
    = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
    = note: the matched value is of type `quaint::error::ErrorKind`

For more information about this error, try `rustc --explain E0004`.

arm64 CLI support

Hey, I'm trying to deploy a docker image that uses prisma-client-rust to aws (in an arm64 machine) and seem to get problems.
Looks like it's downloading the incorrect cli distribution. I'll investigate more later

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|   timestamp   |                                                                                                                                    message                                                                                                                                    |
|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1651665370570 | [cargo-make] INFO - cargo make 0.35.11                                                                                                                                                                                                                                        |
| 1651665373705 | [cargo-make] INFO - Build File: Makefile.toml                                                                                                                                                                                                                                 |
| 1651665373705 | [cargo-make] INFO - Task: migrate-run-prod                                                                                                                                                                                                                                    |
| 1651665373705 | [cargo-make] INFO - Profile: development                                                                                                                                                                                                                                      |
| 1651665373705 | [cargo-make] INFO - Running Task: legacy-migration                                                                                                                                                                                                                            |
| 1651665373713 | [cargo-make] INFO - Running Task: migrate-run-prod                                                                                                                                                                                                                            |
| 1651665373731 | Downloading https://prisma-photongo.s3-eu-west-1.amazonaws.com/prisma-cli-3.12.0-linux.gz to /root/.cache/prisma/binaries/cli/3.12.0/prisma-cli-linux                                                                                                                         |
| 1651665378575 | Downloading https://binaries.prisma.sh/all_commits/22b822189f46ef0dc5c5b503368d1bee01213980/debian-openssl-1.1.x/query-engine.gz to /root/.cache/prisma/binaries/cli/3.12.0/22b822189f46ef0dc5c5b503368d1bee01213980/prisma-query-engine-debian-openssl-1.1.x                 |
| 1651665378926 | Downloading https://binaries.prisma.sh/all_commits/22b822189f46ef0dc5c5b503368d1bee01213980/debian-openssl-1.1.x/migration-engine.gz to /root/.cache/prisma/binaries/cli/3.12.0/22b822189f46ef0dc5c5b503368d1bee01213980/prisma-migration-engine-debian-openssl-1.1.x         |
| 1651665379172 | Downloading https://binaries.prisma.sh/all_commits/22b822189f46ef0dc5c5b503368d1bee01213980/debian-openssl-1.1.x/introspection-engine.gz to /root/.cache/prisma/binaries/cli/3.12.0/22b822189f46ef0dc5c5b503368d1bee01213980/prisma-introspection-engine-debian-openssl-1.1.x |
| 1651665379396 | Downloading https://binaries.prisma.sh/all_commits/22b822189f46ef0dc5c5b503368d1bee01213980/debian-openssl-1.1.x/prisma-fmt.gz to /root/.cache/prisma/binaries/cli/3.12.0/22b822189f46ef0dc5c5b503368d1bee01213980/prisma-prisma-fmt-debian-openssl-1.1.x                     |
| 1651665379492 | thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 8, kind: Uncategorized, message: "Exec format error" }', /usr/local/cargo/git/checkouts/prisma-client-rust-fa967aa5ad0ec391/89df398/cli/src/prisma_cli.rs:40:18                            |
| 1651665379492 | stack backtrace:                                                                                                                                                                                                                                                              |
| 1651665379492 |    0:     0xaaaaabca3448 - std::backtrace_rs::backtrace::libunwind::trace::hb72fa83b7a29f1a7                                                                                                                                                                                  |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/../../backtrace/src/backtrace/libunwind.rs:93:5                                                                                                                             |
| 1651665379492 |    1:     0xaaaaabca3448 - std::backtrace_rs::backtrace::trace_unsynchronized::hbfda2dacac316277                                                                                                                                                                              |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5                                                                                                                                   |
| 1651665379492 |    2:     0xaaaaabca3448 - std::sys_common::backtrace::_print_fmt::hbdc981bfed4ce765                                                                                                                                                                                          |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/sys_common/backtrace.rs:66:5                                                                                                                                                |
| 1651665379492 |    3:     0xaaaaabca3448 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h0ee8113e53dd9501                                                                                                                                               |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/sys_common/backtrace.rs:45:22                                                                                                                                               |
| 1651665379492 |    4:     0xaaaaabcc5d68 - core::fmt::write::hfeafa1b3f4cde44b                                                                                                                                                                                                                |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/core/src/fmt/mod.rs:1190:17                                                                                                                                                         |
| 1651665379492 |    5:     0xaaaaabc9d00c - std::io::Write::write_fmt::h8e498245d185b12b                                                                                                                                                                                                       |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/io/mod.rs:1657:15                                                                                                                                                           |
| 1651665379492 |    6:     0xaaaaabca5718 - std::sys_common::backtrace::_print::hfb8a354270630015                                                                                                                                                                                              |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/sys_common/backtrace.rs:48:5                                                                                                                                                |
| 1651665379492 |    7:     0xaaaaabca5718 - std::sys_common::backtrace::print::h0f1c3f701be8c977                                                                                                                                                                                               |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/sys_common/backtrace.rs:35:9                                                                                                                                                |
| 1651665379492 |    8:     0xaaaaabca5718 - std::panicking::default_hook::{{closure}}::hcaba4274d385417f                                                                                                                                                                                       |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:295:22                                                                                                                                                         |
| 1651665379492 |    9:     0xaaaaabca5360 - std::panicking::default_hook::h89cecd906305ec2a                                                                                                                                                                                                    |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:314:9                                                                                                                                                          |
| 1651665379492 |   10:     0xaaaaabca5d98 - std::panicking::rust_panic_with_hook::haded46e2df0f4fd6                                                                                                                                                                                            |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:698:17                                                                                                                                                         |
| 1651665379492 |   11:     0xaaaaabca5b04 - std::panicking::begin_panic_handler::{{closure}}::he5e693fe5e4ac6b4                                                                                                                                                                                |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:588:13                                                                                                                                                         |
| 1651665379492 |   12:     0xaaaaabca3900 - std::sys_common::backtrace::__rust_end_short_backtrace::hc44d591e7ee285ad                                                                                                                                                                          |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/sys_common/backtrace.rs:138:18                                                                                                                                              |
| 1651665379492 |   13:     0xaaaaabca583c - rust_begin_unwind                                                                                                                                                                                                                                  |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:584:5                                                                                                                                                          |
| 1651665379492 |   14:     0xaaaaab9df7b4 - core::panicking::panic_fmt::hb04515a4b04219bf                                                                                                                                                                                                      |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/core/src/panicking.rs:143:14                                                                                                                                                        |
| 1651665379492 |   15:     0xaaaaab9df858 - core::result::unwrap_failed::hf84f08a5e231dad5                                                                                                                                                                                                     |
| 1651665379492 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/core/src/result.rs:1749:5                                                                                                                                                           |
| 1651665379492 |   16:     0xaaaaaba19b94 - prisma_client_rust_cli::prisma_cli::main::hff2c3c979abb2add                                                                                                                                                                                        |
| 1651665379492 |   17:     0xaaaaab9e3f40 - prisma_client_rust_cli::run::h3ae65fb93de00ed2                                                                                                                                                                                                     |
| 1651665379492 |   18:     0xaaaaab9dff80 - std::sys_common::backtrace::__rust_begin_short_backtrace::h928511540dabcec3                                                                                                                                                                        |
| 1651665379492 |   19:     0xaaaaab9dff6c - std::rt::lang_start::{{closure}}::hf2c6bacf05ad61ee                                                                                                                                                                                                |
| 1651665379492 |   20:     0xaaaaabca2c50 - core::ops::function::impls::<impl core::ops::function::FnOnce<A> for &F>::call_once::hdb45ce9c36440355                                                                                                                                             |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/core/src/ops/function.rs:259:13                                                                                                                                                     |
| 1651665379493 |   21:     0xaaaaabca2c50 - std::panicking::try::do_call::h7e8bb9a5488c007b                                                                                                                                                                                                    |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:492:40                                                                                                                                                         |
| 1651665379493 |   22:     0xaaaaabca2c50 - std::panicking::try::hcc55e9ed15610d77                                                                                                                                                                                                             |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:456:19                                                                                                                                                         |
| 1651665379493 |   23:     0xaaaaabca2c50 - std::panic::catch_unwind::hcf59f097cd8ee652                                                                                                                                                                                                        |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panic.rs:137:14                                                                                                                                                             |
| 1651665379493 |   24:     0xaaaaabca2c50 - std::rt::lang_start_internal::{{closure}}::h8fbfb8ff9e6d08fc                                                                                                                                                                                       |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/rt.rs:128:48                                                                                                                                                                |
| 1651665379493 |   25:     0xaaaaabca2c50 - std::panicking::try::do_call::hb9473916547b0c2e                                                                                                                                                                                                    |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:492:40                                                                                                                                                         |
| 1651665379493 |   26:     0xaaaaabca2c50 - std::panicking::try::hfd0be8714fe2c175                                                                                                                                                                                                             |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panicking.rs:456:19                                                                                                                                                         |
| 1651665379493 |   27:     0xaaaaabca2c50 - std::panic::catch_unwind::hd13ef362c9d4275f                                                                                                                                                                                                        |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/panic.rs:137:14                                                                                                                                                             |
| 1651665379493 |   28:     0xaaaaabca2c50 - std::rt::lang_start_internal::hb2f3ce624f838b60                                                                                                                                                                                                    |
| 1651665379493 |                                at /rustc/7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c/library/std/src/rt.rs:128:20                                                                                                                                                                |
| 1651665379493 |   29:     0xaaaaab9dff3c - main                                                                                                                                                                                                                                               |
| 1651665379493 |   30:     0xffff9dcca218 - __libc_start_main                                                                                                                                                                                                                                  |
| 1651665379493 |   31:     0xaaaaab9dfe34 - <unknown>                                                                                                                                                                                                                                          |
| 1651665379498 | [cargo-make] ERROR - Error while executing command, exit code: 101                                                                                                                                                                                                            |
| 1651665379498 | [cargo-make] WARN - Build Failed.                                                                                                                                                                                                                                             |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Improve explicit many-to-many

It would be nice if you could use explicit m2m relations the same way as implicit ones.
Currently you have to provide extra information for explicit relations, but I think you could probably infer that stuff from the prisma schema?

Null value not handled for EnvValues

With a prisma/schema.prisma file present with a datasource that uses env() from prisma, the generator fails to generate a prisma.rs:

datasource db {
  provider = "postgresql"
  url           = env("DATABASE_URL")
}

Error:

thread 'main' panicked at 'datasources[0].url.value: invalid type: null, expected a string at line 1 column 1136', $HOME/.cargo/git/checkouts/prisma-client-rust-fa967aa5ad0ec391/97d469e/cli/src/lib.rs:109:25

This is on the latest main branch.

The error occurs when serde_json tries to deserialize the input from the schema.prisma file.

Expose CLI as a library to be implemented by consumers

Problem

The current method of installing the prisma-client-rust CLI globally is annoying for two main groups of people:

  • Contributors: Who have to build from their copy of source but also may use it in their own projects, leading to frequent version mismatches
  • Bleeding-edge users: Who may find they have version mismatches between the CLI and lib when updating from one commit to another

Solution

Rather than distributing a CLI binary that can be installed via crates.io, export the CLI as a library that can be included where the user would like, which would be one of multiple places specific to the current repo just like installing prisma from npm does. This has the additional bonus of tying the CLI version to the library version, preventing wrong-version errors and easing the installation process from 1 binary and 1 library to just 1 library.

Same Crate Binary

Inside the project's main crate, a new binary target would be added that calls something like prisma_client_rust::cli::run(). This file would likely exist in src/bin/prisma.rs, since then the user can run cargo run -p prisma -- {command} and likely alias it to cargo prisma {command} instead of prisma-client-rust {command}. This would give full command line access to the prisma CLI. This can be more convenient, but has an issue in that it requires all the CLI code to be bundled with the main binary/library, as binaries are not allowed to have individual dependencies. Hence the next option:

Separate Crate Binary

Requires that the project starts/is using a workspace. Create a separate package - likely called prisma - that contains a single binary which runs prisma_client_rust::cli::run(), which can then be called via cargo run -p prisma --{command}, and then root aliased to cargo prisma {command} so that it can be called anywhere in the project. This approach would allow the CLI code to be put behind a feature flag and not bundled into the main application, which is likely desirable.

Build Script

Running the CLI with something like prisma_client_rust::cli::execute("generate") in the build script would allow for the generated file to always be up to date with the schema, like polytope-labs' implementation does. This, however, does not provide much flexibility with running commands that aren't generate, like db push and migrate dev.
The problem with a build script as outlined above is that the Prisma CLI cannot re-run the file in the same way as a separate binary would be able to re-run. Honestly I'm fine with this seeing as how easy making a separate binary is and the potential benefits in terms of crate size if using a separate crate rather than just a separate binary. However this could still be implemented by calling the separate binary inside the build script and would work just fine!

Multiple double edges produce conflicting implementations of trait

Summary

Multiple double edges produce conflicting implementations of trait.

Example schema

model ModelA {
  id String @id

  edgeOne   ModelB @relation("one", fields: [edgeOneId], references: [id])
  edgeOneId String
  edgeTwo   ModelB @relation("two", fields: [edgeTwoId], references: [id])
  edgeTwoId String
}

model ModelB {
  id String @id

  asEdgeOne ModelA[] @relation("one")
  asEdgeTwo ModelA[] @relation("two")
}

Generated code

impl From<super::model_b::Args> for WithParam {
    fn from(args: super::model_b::Args) -> Self {
        Self::EdgeOne(args)
    }
}
impl From<super::model_b::Args> for WithParam {
    fn from(args: super::model_b::Args) -> Self {
        Self::EdgeTwo(args)
    }
}

// ...

impl From<super::model_a::FindManyArgs> for WithParam {
    fn from(args: super::model_a::FindManyArgs) -> Self {
        Self::AsEdgeOne(args)
    }
}
impl From<super::model_a::FindManyArgs> for WithParam {
    fn from(args: super::model_a::FindManyArgs) -> Self {
        Self::AsEdgeTwo(args)
    }
}

Support (Inbuilt)[] - Value type missmatch with iterator over elements, equals equation (where param) codegen

First of all, thanks for working on this project!

I seem to be getting a pretty generic value type mismatch in the generated prisma -> rust codegen

a value of type `std::vec::Vec<prisma_client_rust::query_core::QueryValue>` cannot be built from an iterator over elements of type `prisma_client_rust::prisma_models::PrismaValue`

value of type `std::vec::Vec<prisma_client_rust::query_core::QueryValue>` cannot be built from `std::iter::Iterator<Item=prisma_client_rust::prisma_models::PrismaValue>`

help: the trait `std::iter::FromIterator<prisma_client_rust::prisma_models::PrismaValue>` is not implemented for `std::vec::Vec<prisma_client_rust::query_core::QueryValue>`rustc(E0277)

These errors pretty much exclusively appear under the equals equation something like

                Self::AtkLevelsEquals(value) => (
                    "ATKLevels".to_string(),
                    SerializedWhereValue::Object(vec![(
                        "equals".to_string(),
                        QueryValue::List(
                            value
                                .into_iter()
                                .map(|v| PrismaValue::Json(serde_json::to_string(&v).unwrap())) // <--- error here
                                .collect(),
                        ),
                    )]),
                ),

Edit

Almost immediately after posting this i noticed the correlation. Seems to happen on Inbuilt[] types such as String[] | Float[] | int[] etc
Have reflected it in the title

panicked at: called `Result::unwrap()` on an `Err` value: Error("invalid type: null")

Hello, after a while I realized that queries can return NULL when a record is not found.
I think it was what is described here. "Error handling: Queries do not return Result types, but will in a future version."
I'm looking at the struct Query impl to see how serde_json could handle this behind the scenes.
Was there any progress on this?
thanks.

Field query functions could overlap model fields

If a schema has fields named not, or or and then we're in trouble ๐Ÿ˜ข

pub struct Post;
impl Post {
    pub fn id() -> PostIdField {
        PostIdField {}
    }
    pub fn content() -> PostContentField {
        PostContentField {}
    }
    pub fn user() -> PostUserField {
        PostUserField {}
    }
    pub fn user_id() -> PostUserIdField {
        PostUserIdField {}
    }
    pub fn not(params: Vec<PostWhereParam>) -> PostWhereParam {
        PostWhereParam::Not(params)
    }
    pub fn or(params: Vec<PostWhereParam>) -> PostWhereParam {
        PostWhereParam::Or(params)
    }
    pub fn and(params: Vec<PostWhereParam>) -> PostWhereParam {
        PostWhereParam::And(params)
    }
}

Serde serialization of query syntax

This would allow for dynamic yet type-safe construction and execution of queries, opening up a wide range of possibilities including a Pothos-style GraphQL + Prisma implementation.

This should probably be behind a feature since making everything ser/de is a lot of generated macro code.

prisma-fmt-debian-openssl-1.1.x was not included into executable

When running prisma-client-rust I keep receiving the following error which prevents me from using this project.

> Downloading Prisma engines for Node-API for debian-openssl-1.1.x [========            ] 39%Error: File or directory '/**/node_modules/prisma/node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x' was not included into executable at compilation stage. Please recompile adding it as asset or script.

I am running on Linux 5.13.0-35-generic #40~20.04.1-Ubuntu.

This error looks the same as steebchen/prisma-client-go#449 but they seem to be struggling to debug it due to it being an intermittent issue. I have managed to make a Dockerfile here which reproduces this issue using prisma-client-rust but I am unable to get the same error when using prisma-client-go in a similar setup.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.