Skip to content

Commit

Permalink
Merge pull request #27 from odroe/26-lowercase-keywords
Browse files Browse the repository at this point in the history
26 lowercase keywords
  • Loading branch information
Seven Du authored Sep 20, 2022
2 parents 42720ff + 7b1a1f6 commit a26c2d7
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 27 deletions.
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

1. Fixed `$transaction` options not being passed.
2. FIxed Using lowercase keywords in schema.prisma cannot generate clients correctly.

## Other

Expand Down
23 changes: 14 additions & 9 deletions bin/src/generator/model_delegate_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import 'package:orm/dmmf.dart' as dmmf;
import 'package:orm/orm.dart' show languageKeywordEncode;

import 'generator_options.dart';
import 'utils/dart_style.dart';
import 'utils/scalar.dart';
import 'utils/schema_type.dart';

String modelDelegateClassname(String model) => '${model}Delegate';
String modelDelegateClassname(String model) =>
'${dartClassnameFixer(model)}Delegate';

class ModelDelegateBuilder {
final GeneratorOptions options;
Expand Down Expand Up @@ -176,15 +178,16 @@ class ModelDelegateBuilder {
);
final Expression fields =
refer('GraphQLFields', 'package:orm/orm.dart').newInstance([
refer('${modelname}ScalarFieldEnum')
refer('${dartClassnameFixer(modelname)}ScalarFieldEnum')
.property('values')
.property('map')
.call([
Method((MethodBuilder methodBuilder) {
methodBuilder.requiredParameters
.add(Parameter((parameterBuilder) {
parameterBuilder.name = 'e';
parameterBuilder.type = refer('${modelname}ScalarFieldEnum');
parameterBuilder.type =
refer('${dartClassnameFixer(modelname)}ScalarFieldEnum');
}));

methodBuilder.body =
Expand Down Expand Up @@ -269,9 +272,10 @@ class ModelDelegateBuilder {
parameterBuilder.type = refer('Map');
}));

methodBuilder.body =
scalarForString(field.outputType.type, false)
.newInstanceNamed('fromJson', [
methodBuilder.body = scalarForString(
dartClassnameFixer(field.outputType.type),
false,
).newInstanceNamed('fromJson', [
refer('e').property('cast').call([]),
]).code;

Expand All @@ -285,9 +289,10 @@ class ModelDelegateBuilder {
return;
}

final Expression deserialize =
scalarForString(field.outputType.type, false)
.newInstanceNamed('fromJson', [
final Expression deserialize = scalarForString(
dartClassnameFixer(field.outputType.type),
false,
).newInstanceNamed('fromJson', [
data.asA(refer('Map')).property('cast').call([]),
]);

Expand Down
15 changes: 6 additions & 9 deletions bin/src/generator/schema_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'package:orm/dmmf.dart' as dmmf;
import 'package:orm/src/runtime/language_keyword.dart';

import 'generator_options.dart';
import 'utils/dart_style.dart';
import 'utils/scalar.dart';
import 'utils/schema_type.dart';

Expand Down Expand Up @@ -60,7 +61,7 @@ class _OutputObjectTypesBuilder {
},
),
);
builder.name = languageKeywordEncode(type.name);
builder.name = dartClassnameFixer(type.name);
builder.implements.add(
code_builder.Reference('JsonSerializable', 'package:orm/orm.dart'));

Expand All @@ -81,7 +82,7 @@ class _OutputObjectTypesBuilder {
));

builder.body = code_builder.Code(
'_\$${languageKeywordEncode(type.name)}FromJson(json)');
'_\$${dartClassnameFixer(type.name)}FromJson(json)');
builder.lambda = true;

builder.factory = true;
Expand All @@ -93,7 +94,7 @@ class _OutputObjectTypesBuilder {
builder.name = 'toJson';
builder.returns = code_builder.Reference('Map<String, dynamic>');
builder.body = code_builder.Code(
'_\$${languageKeywordEncode(type.name)}ToJson(this)');
'_\$${dartClassnameFixer(type.name)}ToJson(this)');
builder.lambda = true;
builder.annotations.add(code_builder.Reference('override'));
},
Expand Down Expand Up @@ -188,7 +189,7 @@ class _InputObjectTypesBuilder {
void _buildInputTypes(List<dmmf.InputType> inputs) {
for (final dmmf.InputType input in inputs) {
library.body.add(code_builder.Class((code_builder.ClassBuilder updates) {
updates.name = languageKeywordEncode(input.name);
updates.name = dartClassnameFixer(input.name);
updates.implements.add(
code_builder.Reference('JsonSerializable', 'package:orm/orm.dart'));

Expand Down Expand Up @@ -302,12 +303,8 @@ class _EnumBuilder {
}

library.body.add(code_builder.Enum((code_builder.EnumBuilder updates) {
updates.name = languageKeywordEncode(element.name);
updates.name = dartClassnameFixer(element.name);
updates.values.addAll(element.values.map(_buildEnumValue));
// updates.annotations.add(code_builder.TypeReference((updates) {
// updates.symbol = 'JsonEnum';
// updates.url = 'package:json_annotation/json_annotation.dart';
// }).newInstance([]));
}));
}
}
Expand Down
25 changes: 25 additions & 0 deletions bin/src/generator/utils/dart_style.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import 'package:orm/src/runtime/language_keyword.dart';

/// Fix a dart class name.
///
/// Example:
/// a -> A
/// _a -> $A
/// a_ -> A_
String dartClassnameFixer(String name) {
final String fixed = languageKeywordEncode(name);

return _charToUpperCase(fixed, 0);
}

String _charToUpperCase(String name, int index) {
if (name.length == 1) return name.toUpperCase();

if (RegExp(r'[a-zA-Z]').hasMatch(name[index])) {
return name[index].toUpperCase() + name.substring(index + 1);
} else if ((index + 1) >= name.length) {
return name;
}

return name[index] + _charToUpperCase(name, index + 1);
}
22 changes: 17 additions & 5 deletions bin/src/generator/utils/scalar.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'package:code_builder/code_builder.dart';
import 'package:orm/dmmf.dart';

import 'dart_style.dart';

final Map<String, Reference> _references = {
'string': Reference('String'),
'float': Reference('double'),
Expand Down Expand Up @@ -35,32 +37,42 @@ TypeReference scalarForString(String name, [bool isNullable = false]) {
}

TypeReference scalar(SchemaType schemaType, [bool isNullable = false]) {
final SchemaType resolvedSchemaType = SchemaType(
isList: schemaType.isList,
type: schemaType.location == FieldLocation.scalar
? schemaType.type
: dartClassnameFixer(schemaType.type),
location: schemaType.location,
namespace: schemaType.namespace,
);

if (isNullable) {
// See https://github.com/dart-lang/code_builder/issues/315
// If the issue is fixed, then PrismaNullable can be removed.
return TypeReference((TypeReferenceBuilder updates) {
updates.symbol = 'PrismaNullable';
updates.url = 'package:orm/orm.dart';
updates.types.add(scalar(schemaType, false));
updates.types.add(scalar(resolvedSchemaType, false));
});
} else if (schemaType.isList) {
} else if (resolvedSchemaType.isList) {
return TypeReference((TypeReferenceBuilder updates) {
updates.symbol = 'List';

final SchemaType newType = SchemaType.fromJson({
...schemaType.toJson(),
...resolvedSchemaType.toJson(),
'isList': false,
});

updates.types.add(scalar(newType, isNullable));
});
}

final Reference? reference = _references[schemaType.type.toLowerCase()];
final Reference? reference =
_references[resolvedSchemaType.type.toLowerCase()];
if (reference is TypeReference) return reference;

return TypeReference((TypeReferenceBuilder updates) {
updates.symbol = reference?.symbol ?? schemaType.type;
updates.symbol = reference?.symbol ?? resolvedSchemaType.type;
updates.url = reference?.url;
});
}
6 changes: 4 additions & 2 deletions bin/src/generator/utils/schema_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import 'package:orm/dmmf.dart';

import 'scalar.dart';

Reference schemaTypeResolver(List<SchemaType> types,
[bool isNullable = false]) {
Reference schemaTypeResolver(
Iterable<SchemaType> types, [
bool isNullable = false,
]) {
if (types.length == 1) {
return scalar(types.first, isNullable);
}
Expand Down
2 changes: 1 addition & 1 deletion example/simple/lib/src/generated/prisma_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16945,7 +16945,7 @@ final _i3.Document dmmf = _i3.Document.fromJson(<String, dynamic>{
},
});
const String schema =
'generator client {\n provider = "prisma-client-dart"\n output = "../lib/src/generated"\n previewFeatures = ["interactiveTransactions"]\n}\n\ndatasource db {\n provider = "postgresql"\n url = env("DATABASE_URL")\n}\n\nenum Sex {\n man\n woman\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n name String\n createdAt DateTime @default(now())\n sex Sex @default(woman)\n posts Post[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n authorId Int\n content String\n published Boolean\n created_at DateTime @default(now())\n author User @relation(fields: [authorId], references: [id])\n}\n';
'generator client {\n provider = "prisma-client-dart"\n output = "../lib/src/generated"\n previewFeatures = ["interactiveTransactions"]\n}\n\ndatasource db {\n provider = "postgresql"\n url = env("DATABASE_URL")\n}\n\nenum Sex {\n man\n woman\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n name String\n createdAt DateTime @default(now())\n sex Sex @default(woman)\n posts Post[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n authorId Int\n content String\n published Boolean\n created_at DateTime @default(now())\n author User @relation(fields: [authorId], references: [id])\n}\n';
const String _executable =
r'/Users/seven/workspace/prisma/example/simple/.dart_tool/prisma/query-engine';

Expand Down
2 changes: 1 addition & 1 deletion example/simple/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ model User {
id Int @id @default(autoincrement())
name String
createdAt DateTime @default(now())
sex Sex @default(woman)
sex Sex @default(woman)
posts Post[]
}

Expand Down
34 changes: 34 additions & 0 deletions test/bin/generator/utils/dart_style_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import 'package:test/expect.dart';
import 'package:test/scaffolding.dart';

import '../../../../bin/src/generator/utils/dart_style.dart';

void main() {
test('test single char', () {
expect(dartClassnameFixer('a'), 'A');
});

test('test single char with underscore', () {
expect(dartClassnameFixer('_a'), r'$A');
});

test('test single char with underscore', () {
expect(dartClassnameFixer('a_'), r'A_');
});

test('test multiple char', () {
expect(dartClassnameFixer('abc'), r'Abc');
});

test('test multiple char with underscore', () {
expect(dartClassnameFixer('_abc'), r'$Abc');
});

test('test multiple char with underscore', () {
expect(dartClassnameFixer('abc_'), r'Abc_');
});

test('test multiple char with underscore', () {
expect(dartClassnameFixer('_abc_'), r'$Abc_');
});
}
File renamed without changes.

0 comments on commit a26c2d7

Please sign in to comment.