Skip to content

Commit

Permalink
fix: improve name generation for prisma types (#849)
Browse files Browse the repository at this point in the history
<!--
Pull requests are squashed and merged using:
- their title as the commit message
- their description as the commit body

Having a good title and description is important for the users to get
readable changelog.
-->

<!-- 1. Explain WHAT the change is about -->

Solve
[MET-657](https://linear.app/metatypedev/issue/MET-657/sdk-improve-generated-titles-for-prisma-types)

<!-- 2. Explain WHY the change cannot be made simpler -->



<!-- 3. Explain HOW users should update their code -->

#### Migration notes

...

- [ ] The change comes with new or modified tests
- [ ] Hard-to-understand functions have explanatory comments
- [ ] End-user documentation is updated to reflect the change
  • Loading branch information
Natoandro authored Sep 24, 2024
1 parent ee0b2c4 commit 24eb721
Show file tree
Hide file tree
Showing 63 changed files with 1,932 additions and 1,857 deletions.
36 changes: 20 additions & 16 deletions ghjk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ env("main")
...stdDeps(),
installs.python_latest,
installs.node,
installs.rust_stable,
installs.rust_stable
);

env("_rust").install(
// use rustup for the actual toolchain
ports.protoc({ version: "v28.2" }),
ports.cmake()[0],
ports.cmake()[0]
);

if (Deno.build.os == "linux" && !Deno.env.has("NO_MOLD")) {
Expand All @@ -46,7 +46,7 @@ if (Deno.build.os == "linux" && !Deno.env.has("NO_MOLD")) {
env("_ecma").install(
installs.node,
ports.pnpm({ version: "v9.4.0" }),
ports.npmi({ packageName: "node-gyp", version: "10.0.1" })[0],
ports.npmi({ packageName: "node-gyp", version: "10.0.1" })[0]
);

env("_python").install(
Expand All @@ -58,7 +58,7 @@ env("_python").install(
ports.pipi({
packageName: "poetry",
version: "1.8.3",
})[0],
})[0]
);

env("_wasm").install(
Expand All @@ -77,7 +77,7 @@ env("_wasm").install(
ports.npmi({
packageName: "@bytecodealliance/jco",
version: "1.3.0",
})[0],
})[0]
);

env("oci").inherit(["_rust", "_wasm"]);
Expand All @@ -96,7 +96,7 @@ env("ci")
crateName: "cross",
version: "0.2.5",
locked: true,
}),
})
);

env("dev")
Expand All @@ -105,7 +105,7 @@ env("dev")
ports.act(),
ports.cargobi({ crateName: "whiz", locked: true }),
ports.cargobi({ crateName: "wit-deps-cli", locked: true }),
ports.cargobi({ crateName: "git-cliff", locked: true }),
ports.cargobi({ crateName: "git-cliff", locked: true })
);

task("version-print", () => console.log(METATYPE_VERSION), {
Expand All @@ -126,7 +126,7 @@ task("version-bump", async ($) => {

if (!bumps.includes(bump)) {
throw new Error(
`invalid argument "${bump}", valid are: ${bumps.join(", ")}`,
`invalid argument "${bump}", valid are: ${bumps.join(", ")}`
);
}

Expand All @@ -136,15 +136,15 @@ task("version-bump", async ($) => {
bump as semver.ReleaseType,
{
prerelease: "rc",
},
),
}
)
);

$.logStep(`Bumping ${METATYPE_VERSION}${newVersion}`);
const lines = [[/^(export const METATYPE_VERSION = ").*(";)$/, newVersion]];
if (bump === "prerelease") {
$.logStep(
`Bumping published version ${PUBLISHED_VERSION}${METATYPE_VERSION}`,
`Bumping published version ${PUBLISHED_VERSION}${METATYPE_VERSION}`
);
lines.push([
/^(export const PUBLISHED_VERSION = ").*(";)$/,
Expand All @@ -160,10 +160,14 @@ task("version-bump", async ($) => {
await $`ghjk x lock-sed`;
});

task("b", async ($) => {
await $`cargo b --target wasm32-unknown-unknown --package typegraph-ng`;
await $`wasm-tools component new "target/wasm32-unknown-unknown/debug/typegraph_ng.wasm"
task(
"b",
async ($) => {
await $`cargo b --target wasm32-unknown-unknown --package typegraph-ng`;
await $`wasm-tools component new "target/wasm32-unknown-unknown/debug/typegraph_ng.wasm"
-o ./target/ng.wasm
`;
// --adapt wasi_snapshot_preview1=./tmp/wasi_snapshot_preview1.reactor.wasm
}, { inherit: "_wasm" });
// --adapt wasi_snapshot_preview1=./tmp/wasi_snapshot_preview1.reactor.wasm
},
{ inherit: "_wasm" }
);
60 changes: 44 additions & 16 deletions src/typegraph/core/src/runtimes/prisma/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: MPL-2.0

use std::{
cell::{Cell, OnceCell, Ref, RefCell, RefMut},
cell::{OnceCell, Ref, RefCell, RefMut},
collections::HashMap,
rc::{Rc, Weak},
};
Expand All @@ -11,9 +11,12 @@ use crate::{typegraph::TypegraphContext, wit::runtimes as wit};
use common::typegraph::runtimes::prisma as cm;
use indexmap::{map::Entry, IndexMap, IndexSet};

use super::model::{InjectionHandler, Property, RelationshipProperty, ScalarProperty};
use super::relationship::discovery::CandidatePair;
use super::relationship::RelationshipModel;
use super::{
model::{InjectionHandler, Property, RelationshipProperty, ScalarProperty},
relationship::discovery::RelationshipName,
};
use crate::errors::Result;
use crate::types::TypeId;

Expand Down Expand Up @@ -53,7 +56,6 @@ pub struct PrismaContext {
pub relationships: IndexMap<String, Relationship>,
pub typegen_cache: OnceCell<Weak<RefCell<HashMap<String, TypeId>>>>, // shared
complete_registrations: IndexSet<TypeId>,
counter: Cell<usize>,
}

impl PrismaContext {
Expand Down Expand Up @@ -88,17 +90,49 @@ impl PrismaContext {
}
}

pub fn register_relationship(
&mut self,
name: RelationshipName,
relationship: Relationship,
) -> Result<()> {
use indexmap::map::Entry as E;
use RelationshipName::*;
match name {
User(name) => match self.relationships.entry(name.clone()) {
E::Occupied(rel) => {
let rel = rel.get();
return Err(format!("relationship name '{}' already used between {} and {}, please provide another name",
name, rel.left.model_name, rel.right.model_name).into());
}
E::Vacant(e) => {
e.insert(relationship);
}
},

Generated(name) => match self.relationships.entry(name.clone()) {
E::Occupied(rel) => {
let rel = rel.get();
return Err(format!("relationship name '{}' already used between {} and {}, please provide a name",
name, rel.left.model_name, rel.right.model_name).into());
}
E::Vacant(e) => {
e.insert(relationship);
}
},
}

Ok(())
}

pub fn register_pair(&mut self, pair: CandidatePair) -> Result<bool> {
if !self.is_registered(&pair)? {
println!("registering");
let id = self.next_id();
let pair = pair.ordered()?;

let rel_name = pair.rel_name(id)?;
let rel_name = pair.rel_name()?;
let CandidatePair(left, right) = pair;

let relationship = Relationship {
name: rel_name.clone(),
name: rel_name.to_string(),
left: RelationshipModel {
model_type: left.model.type_id(),
model_name: left.model.type_name(),
Expand All @@ -115,20 +149,20 @@ impl PrismaContext {
},
};

self.relationships.insert(rel_name.clone(), relationship);
self.register_relationship(rel_name.clone(), relationship)?;

{
let mut left_model = left.model.borrow_mut();
left_model
.relationships
.insert(right.field_name.clone(), rel_name.clone());
.insert(right.field_name.clone(), rel_name.to_string());
}

{
let mut right_model = right.model.borrow_mut();
right_model
.relationships
.insert(left.field_name.clone(), rel_name.clone());
.insert(left.field_name.clone(), rel_name.into());
}

Ok(true)
Expand Down Expand Up @@ -188,12 +222,6 @@ impl PrismaContext {
}
}

fn next_id(&self) -> usize {
let id = self.counter.get() + 1;
self.counter.set(id);
id
}

fn convert_scalar_prop(
&self,
ctx: &mut TypegraphContext,
Expand Down
40 changes: 33 additions & 7 deletions src/typegraph/core/src/runtimes/prisma/relationship/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,22 +174,48 @@ impl PrismaContext {
#[derive(Debug)]
pub struct CandidatePair(pub Candidate, pub Candidate);

#[derive(Debug, Clone)]
pub enum RelationshipName {
User(String),
Generated(String),
}

impl std::fmt::Display for RelationshipName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use RelationshipName::*;
match self {
User(name) => write!(f, "{}", name),
Generated(name) => write!(f, "{}", name),
}
}
}

impl From<RelationshipName> for String {
fn from(name: RelationshipName) -> Self {
match name {
RelationshipName::User(name) => name,
RelationshipName::Generated(name) => name,
}
}
}

impl CandidatePair {
pub fn rel_name(&self, id: usize) -> Result<String> {
pub fn rel_name(&self) -> Result<RelationshipName> {
use RelationshipName::*;
match (
&self.0.property.relationship_attributes.name,
&self.1.property.relationship_attributes.name,
) {
(None, None) => Ok(format!(
"__rel_{}_{}_{id}",
(None, None) => Ok(Generated(format!(
"rel_{}_{}",
self.1.model.type_name(),
self.0.model.type_name()
)),
(Some(a), None) => Ok(a.clone()),
(None, Some(b)) => Ok(b.clone()),
))),
(Some(a), None) => Ok(User(a.clone())),
(None, Some(b)) => Ok(User(b.clone())),
(Some(a), Some(b)) => {
if a == b {
Ok(a.clone())
Ok(User(a.clone()))
} else {
// unreachable!
Err(format!("conflicting relationship names: {} and {}", a, b).into())
Expand Down
8 changes: 4 additions & 4 deletions src/typegraph/core/src/runtimes/prisma/relationship/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ mod test {

assert_eq!(ctx.relationships.len(), 1);
let (name, rel) = ctx.relationships.iter().next().unwrap();
assert_eq!(name, "__rel_Post_User_1");
assert_eq!(name, "rel_Post_User");
assert_eq!(rel.left.model_name, "User");
assert_eq!(rel.right.model_name, "Post");

Expand Down Expand Up @@ -206,7 +206,7 @@ mod test {
let relationships = ctx.relationships;
assert_eq!(relationships.len(), 1);
let (name, rel) = relationships.iter().next().unwrap();
assert_eq!(name, "__rel_User_Profile_1");
assert_eq!(name, "rel_User_Profile");
assert_eq!(rel.left.model_name, "Profile");
assert_eq!(rel.right.model_name, "User");

Expand Down Expand Up @@ -237,7 +237,7 @@ mod test {

assert_eq!(ctx.relationships.len(), 1);
let (name, rel) = ctx.relationships.iter().next().unwrap();
assert_eq!(name, "__rel_User_Profile_1");
assert_eq!(name, "rel_User_Profile");
assert_eq!(rel.left.model_name, "Profile");
assert_eq!(rel.right.model_name, "User");

Expand All @@ -259,7 +259,7 @@ mod test {

assert_eq!(ctx.relationships.len(), 1);
let (name, rel) = ctx.relationships.iter().next().unwrap();
assert_eq!(name, "__rel_Node_Node_1");
assert_eq!(name, "rel_Node_Node");
assert_eq!(rel.left.model_name, "Node");
assert_eq!(rel.right.model_name, "Node");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl TypeGen for Take {
}

fn name(&self) -> String {
"_Take".to_string()
"_take".to_string()
}
}

Expand All @@ -28,7 +28,7 @@ impl TypeGen for Skip {
}

fn name(&self) -> String {
"_Skip".to_string()
"_skip".to_string()
}
}

Expand All @@ -54,7 +54,7 @@ impl TypeGen for Distinct {

fn name(&self) -> String {
let model_name = self.0.name().unwrap().unwrap();
format!("_KeysOf_{model_name}")
format!("{model_name}_keys_union")
}
}

Expand Down Expand Up @@ -91,6 +91,6 @@ impl TypeGen for Cursor {

fn name(&self) -> String {
let model_name = self.model_id.name().unwrap().unwrap();
format!("_{}_Cursor", model_name)
format!("{}_cursor", model_name)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl TypeGen for CountOutput {

fn name(&self) -> String {
let model_name = self.model_id.name().unwrap().unwrap();
format!("_{}_AggrCount", model_name)
format!("{}_count_aggregate", model_name)
}
}

Expand Down Expand Up @@ -93,7 +93,10 @@ impl TypeGen for NumberAggregateOutput {

fn name(&self) -> String {
let model_name = self.model_id.name().unwrap().unwrap();
let suffix = if self.avg { "_avg" } else { "" };
format!("_{model_name}_NumberAgg{suffix}")
if self.avg {
format!("{}_avg_aggregate", model_name)
} else {
format!("{}_number_aggregate", model_name)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ impl TypeGen for Count {
}

fn name(&self) -> String {
"_Count".to_string()
"_count".to_string()
}
}
Loading

0 comments on commit 24eb721

Please sign in to comment.