Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for CONSTANT_CASE formatting #65

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Options:
-V, --version hint: you have v2.1.0
-h, --help display help for command
-------------------------
Supported case conventions: ["pascal", "camel", "snake"].
Supported case conventions: ["pascal", "camel", "snake", "constant"].
Additionally, append ',plural' after any case-convention selection to mark case convention as pluralized.
> For instance:
--map-table-case=snake,plural
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prisma-case-format",
"version": "2.2.1",
"version": "2.2.2",
"description": "Give your introspected schema.prisma sane casing conventions",
"main": "./dist/cli.js",
"repository": {
Expand Down
13 changes: 11 additions & 2 deletions src/convention-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { camelCase, pascalCase, snakeCase } from 'change-case';
import { camelCase, pascalCase, snakeCase, constantCase } from 'change-case';
import { CaseChange, asPluralized, asSingularized } from './caseConventions';
import { existsSync, readFileSync } from 'fs';
import * as jsyaml from 'js-yaml';
Expand All @@ -17,6 +17,9 @@ export function tryGetTableCaseConvention(raw_type: string): [CaseChange?, Error
case 'snake':
kase = snakeCase;
break;
case 'constant':
kase = constantCase;
break;
case 'false':
case 'true':
case 'disable':
Expand All @@ -38,7 +41,7 @@ export function tryGetTableCaseConvention(raw_type: string): [CaseChange?, Error
}

export const SUPPORTED_CASE_CONVENTIONS_MESSAGE = `-------------------------
Supported case conventions: ["pascal", "camel", "snake"].
Supported case conventions: ["pascal", "camel", "snake", "constant"].
Additionally, append ',plural' after any case-convention selection to mark case convention as pluralized.
For instance:
--map-table-case=snake,plural
Expand Down Expand Up @@ -283,6 +286,9 @@ export class ConventionStore {
if (this.children?.hasOwnProperty(camelCase(next))) {
return this.children[camelCase(next)]._recurse(k, rest);
}
if (this.children?.hasOwnProperty(constantCase(next))) {
return this.children[constantCase(next)]._recurse(k, rest);
}

const haystack = this.children ?? {};
for (const key in haystack) {
Expand All @@ -299,6 +305,9 @@ export class ConventionStore {
if (regex.test(camelCase(next))) {
return this.children![camelCase(next)]._recurse(k, rest);
}
if (regex.test(constantCase(next))) {
return this.children![constantCase(next)]._recurse(k, rest);
}
}
return undefined;
}
Expand Down
202 changes: 201 additions & 1 deletion test/__snapshots__/convention-transformer.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ exports[`disable2 1`] = `
id String @id @default(cuid())
passwordsSingular String[] @map("passwords_singular")
requestsSingulars String[] @map("requests_singular")
columnsSingular String[]
columnsSingular String[] @map("columns_singular")
pluralsPlurals String[] @map("pluralsPlural")
plurals String[] @map("plural")
}
"
`;
Expand Down Expand Up @@ -246,6 +247,104 @@ model Business {
"
`;

exports[`it can enforce a specified case convention on all fields of all tables (constantCase): constantCase 1`] = `
"datasource db {
provider = "sqlite"
url = "file:database.db"
}

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

model DemoIt {
id Int @id @map("ID")
dataField String @map("DATA_FIELD")
}
"
`;

exports[`it can enforce a specified case convention on all fields of all tables (constantCase): constantCase 2`] = `
"datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Projects {
id Int @id @default(autoincrement()) @map("ID")
name String? @map("NAME") @db.VarChar
jiraIssues JiraIssues[]

@@map("projects")
}

model JiraIssues {
id Int @id @default(autoincrement()) @map("ID")
jiraIntegrationId Int? @map("JIRA_INTEGRATION_ID")
projectId Int @map("PROJECT_ID")
projects Projects? @relation(fields: [projectId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "jira_issues_projects_fkey")

@@map("jira_issues")
}

model FieldKey {
key String @map("KEY")
type String @map("TYPE") // str, num, bool
formId String @map("FORM_ID") @db.Uuid
form Form @relation(references: [id], fields: [formId], onDelete: Cascade)

@@id([key, formId])
@@map("field_key")
}
"
`;

exports[`it can enforce a specified case convention on all fields of all tables (constantCase): constantCase 3`] = `
"datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Business {
id String @id(map: "BusinessId") @default(dbgenerated("gen_random_uuid()")) @map("ID") @db.Uuid
languageCode String @map("LANGUAGE_CODE") @db.Char(2)
currencyCode String @map("CURRENCY_CODE") @db.Char(3)
createdAt DateTime @default(now()) @map("CREATED_AT") @db.Timestamptz(0)
name String @map("NAME") @db.VarChar(64)
language String[] @default([]) @map("LANGUAGE") @db.Char(2)
phone String @map("PHONE") @db.VarChar(15)
address String? @map("ADDRESS") @db.VarChar(250)
billingName String? @map("BILLING_NAME") @db.VarChar(64)
billingAddress String? @map("BILLING_ADDRESS") @db.VarChar(250)
taxOffice String? @map("TAX_OFFICE") @db.VarChar(64)
taxId String? @map("TAX_ID") @db.VarChar(64)
defaultTaxRate Decimal? @map("DEFAULT_TAX_RATE") @db.Decimal(8, 6)
isActive Boolean @default(true) @map("IS_ACTIVE")
batchOperation BatchOperation[]
currency Currency @relation(fields: [currencyCode], references: [code], onUpdate: Restrict, map: "BusinessCurrency")
language Language @relation(fields: [languageCode], references: [code], onUpdate: Restrict, map: "BusinessLanguage")
ingredientCategory IngredientCategory[]
itemCategory ItemCategory[]
optionCategory OptionCategory[]
profile Profile[]
recipe Recipe[]
tab Tab[]
targetGroup TargetGroup[]

@@schema("public")
}
"
`;

exports[`it can enforce a specified case convention on all fields of all tables (pascalCase): pascalCase 1`] = `
"datasource db {
provider = "sqlite"
Expand Down Expand Up @@ -543,6 +642,107 @@ model Business {
"
`;

exports[`it can enforce a specified case convention on all table names (constantCase): constantCase 1`] = `
"datasource db {
provider = "sqlite"
url = "file:database.db"
}

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

model DemoIt {
id Int @id
dataField String @map("data_field")

@@map("DEMO_IT")
}
"
`;

exports[`it can enforce a specified case convention on all table names (constantCase): constantCase 2`] = `
"datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Projects {
id Int @id @default(autoincrement())
name String? @db.VarChar
jiraIssues JiraIssues[]

@@map("PROJECTS")
}

model JiraIssues {
id Int @id @default(autoincrement())
jiraIntegrationId Int? @map("jira_integration_id")
projectId Int @map("project_id")
projects Projects? @relation(fields: [projectId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "jira_issues_projects_fkey")

@@map("JIRA_ISSUES")
}

model FieldKey {
key String
type String // str, num, bool
formId String @map("form_id") @db.Uuid
form Form @relation(references: [id], fields: [formId], onDelete: Cascade)

@@id([key, formId])
@@map("FIELD_KEY")
}
"
`;

exports[`it can enforce a specified case convention on all table names (constantCase): constantCase 3`] = `
"datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Business {
id String @id(map: "BusinessId") @default(dbgenerated("gen_random_uuid()")) @db.Uuid
languageCode String @db.Char(2)
currencyCode String @db.Char(3)
createdAt DateTime @default(now()) @db.Timestamptz(0)
name String @db.VarChar(64)
language String[] @default([]) @db.Char(2)
phone String @db.VarChar(15)
address String? @db.VarChar(250)
billingName String? @db.VarChar(64)
billingAddress String? @db.VarChar(250)
taxOffice String? @db.VarChar(64)
taxId String? @db.VarChar(64)
defaultTaxRate Decimal? @db.Decimal(8, 6)
isActive Boolean @default(true)
batchOperation BatchOperation[]
currency Currency @relation(fields: [currencyCode], references: [code], onUpdate: Restrict, map: "BusinessCurrency")
language Language @relation(fields: [languageCode], references: [code], onUpdate: Restrict, map: "BusinessLanguage")
ingredientCategory IngredientCategory[]
itemCategory ItemCategory[]
optionCategory OptionCategory[]
profile Profile[]
recipe Recipe[]
tab Tab[]
targetGroup TargetGroup[]

@@map("BUSINESS")
@@schema("public")
}
"
`;

exports[`it can enforce a specified case convention on all table names (pascalCase): pascalCase 1`] = `
"datasource db {
provider = "sqlite"
Expand Down
18 changes: 16 additions & 2 deletions test/convention-transformer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { readFileSync } from 'fs';

import { join } from 'path';

import { camelCase, pascalCase, snakeCase } from 'change-case';
import { camelCase, pascalCase, snakeCase, constantCase } from 'change-case';
import { CaseChange, ConventionTransformer } from '../src/convention-transformer';
import { formatSchema } from '@prisma/internals';

Expand Down Expand Up @@ -109,7 +109,7 @@ test('it can account for comments on model lines', () => {
});

const supported_case_conventions: { caseConvention: CaseChange }[] = [
{ caseConvention: snakeCase }, { caseConvention: camelCase }, { caseConvention: pascalCase }];
{ caseConvention: snakeCase }, { caseConvention: camelCase }, { caseConvention: pascalCase }, { caseConvention: constantCase }];
/**
* !!Warning!! Jest snapshots are _almost_ an anti-pattern. This is because if
* you rename the test case, and introduce a bug, the bug is now valid to Jest.
Expand Down Expand Up @@ -315,6 +315,20 @@ describe('must properly bring enum name to', () => {
expect(err).toBeFalsy();
expect(result?.includes('enum post_type')).toBeTruthy();
});

test('CONSTANT_CASE', () => {
const file_contents = getFixture('enum');

const store = ConventionStore.fromConventions({
...defaultConventions(),
tableCaseConvention: pascalCase,
fieldCaseConvention: camelCase,
enumCaseConvention: constantCase,
});
const [result, err] = ConventionTransformer.migrateCaseConventions(file_contents, store);
expect(err).toBeFalsy();
expect(result?.includes('enum POST_TYPE')).toBeTruthy();
});
});

describe('must properly map enum name to ', () => {
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"target": "ES2018" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"esnext"
Expand Down