Skip to content

Commit

Permalink
fix (generator): correctly capitalise table named model (#515)
Browse files Browse the repository at this point in the history
This PR fixes the bug for a table named "model", described by a user on
[Discord](https://discord.com/channels/933657521581858818/933657523049885698/1156342498453639260).
We were parsing the Prisma schema in order to capitalise model names but
if the model name itself was "model" we would capitalise the "model"
keyword instead of the model name "model". This is fixed by replacing
the exact match in the string instead of replacing the first occurrence
of the table name.

Also extended the unit test to check this case.
  • Loading branch information
kevin-dp authored Oct 2, 2023
1 parent 783b550 commit 226c004
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-planes-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"electric-sql": patch
---

Fix bug for table named "model"
7 changes: 5 additions & 2 deletions clients/typescript/src/cli/migrations/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,8 @@ export function doPascalCaseTableNames(lines: string[]): string[] {
const replacements: Map<string, string> = new Map() // maps table names to their PascalCased model name
const modelNameToDbName: Map<string, string> = new Map() // maps the PascalCased model names to their original table name

const getModelName = (ln: string) => ln.match(/^\s*model\s+(\w+)/)?.[1]
const modelRegex = /^\s*model\s+(\w+)\s*{/
const getModelName = (ln: string) => ln.match(modelRegex)?.[1]

lines.forEach((ln, idx) => {
const tableName = getModelName(ln)
Expand All @@ -320,7 +321,9 @@ export function doPascalCaseTableNames(lines: string[]): string[] {
: capitaliseFirstLetter(tableName) // always capitalise first letter

// Replace the model name on this line
const newLn = ln.replace(tableName, modelName)
const newLn = ln.replace(modelRegex, (_, _tableName) => {
return `model ${modelName} {`
})
lines[idx] = newLn

replacements.set(tableName, modelName)
Expand Down
9 changes: 9 additions & 0 deletions clients/typescript/test/cli/migrations/migrate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ model user_profile {
userId Int @unique
user user? @relation(fields: [userId], references: [id])
}
model model {
id Int @id
}
`

const expectedPrismaSchema = `
Expand Down Expand Up @@ -97,6 +101,11 @@ model UserProfile {
userId Int @unique
user User? @relation(fields: [userId], references: [id])
}
model Model {
@@map("model")
id Int @id
}
`

test('migrator correctly PascalCases model names', (t) => {
Expand Down

0 comments on commit 226c004

Please sign in to comment.