Skip to content

Commit

Permalink
Merge pull request #24 from odroe/23-nullable-fields-generating-broke…
Browse files Browse the repository at this point in the history
…n-field-implementations

Fixed #23 & input object types without `PrismaUnion` wrapper.
  • Loading branch information
Seven Du authored Sep 20, 2022
2 parents 2e8adf7 + 236e888 commit 1d0abc3
Show file tree
Hide file tree
Showing 24 changed files with 18,181 additions and 303 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: test
on: [push, pull_request]
jobs:
test:
strategy:
matrix:
sdk:
- stable
- 2.18.0
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dart-lang/setup-dart@v1
with:
sdk: ${{ matrix.sdk }}
- name: Cache prisma engines
uses: actions/cache@v3
with:
path: .dart_tool/prisma
key: ${{ runner.os }}-${{ runner.arch }}-prisma-engines-${{ hashFiles('**/lib/version.dart') }}
- name: Install dependencies
run: dart pub get
- name: Pre-download engines
run: dart run bin/orm.dart precache
- name: Run tests
run: dart test -r github
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
## 2.2.0

🌟 Help us spread the word about [Prisma ORM for Dart](https://github.com/odroe/prisma-dart) by starring the repo or [Tweeting](https://twitter.com/intent/tweet?text=Check%20out%20the%20latest%20@prisma%20ORM%20for%20Dart%20release%20v2.2.0🚀%0D%0A%0D%0Ahttps://github.com/odroe/prisma-dart/releases/tag/2.2.0) about the release. 🌟

### Major improvements:

Input object Types without `PrismaUnion` wrapper, Before:
```dart
final User user = await prisma.user.create(
data: PrismaUnion(
zero: UserCreateInput(name: 'odroe'),
),
);
```
After:
```dart
final User user = await prisma.user.create(
data: UserCreateInput(name: 'odroe'),
);
```

### Bug fixes:

- Nullable fields generating broken field implementations - [#23](https://github.com/odroe/prisma-dart/issues/23)

### Features:

- Add `precache` command, Populate the Prisma engines cache of binary artifacts.

## 2.1.3

🌟 Help us spread the word about [Prisma ORM for Dart](https://github.com/odroe/prisma-dart) by starring the repo or [Tweeting](https://twitter.com/intent/tweet?text=Check%20out%20the%20latest%20@prisma%20ORM%20for%20Dart%20release%20v2.1.3🚀%0D%0A%0D%0Ahttps://github.com/odroe/prisma-dart/releases/tag/2.1.3) about the release. 🌟
Expand Down
38 changes: 19 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ Next-generation ORM for Dart Native & Flutter | PostgreSQL, MySQL, MariaDB, SQL

[![Pub Version](https://img.shields.io/pub/v/orm?label=latest)](https://pub.dev/packages/orm)
[![GitHub license](https://img.shields.io/github/license/odroe/prisma-dart)](https://github.com/odroe/prisma-dart/blob/main/LICENSE)
[![test](https://github.com/odroe/prisma-dart/actions/workflows/test.yaml/badge.svg)](https://github.com/odroe/prisma-dart/actions/workflows/test.yaml)

## What is it?

Expand All @@ -12,11 +13,11 @@ Prisma is a **next-generation ORM** that consists of these tools:
- **Prisma Query Engine** - Prisma query engines wrapper:
1. **Binary Engine** - Only for Dart Native.
2. **Dynamic Library Engine** - Supported for Dart Native and Flutter Native. `❌ Waiting`
3. **Prisma Data Proxy Engint** - Supported all platforms. `❌ Waiting`
3. **Prisma Data Proxy Engint** - Supported all platforms. `❌ Waiting` See [Add Data proxy engine support](https://github.com/odroe/prisma-dart/issues/22).

## Getting started

> **Prerequisites**: Dart SDK `>=2.17.6 <3.0.0`
> **Prerequisites**: Dart SDK `>=2.18.0 <3.0.0`
### 1. Create Dart project and setup Prisma

Expand Down Expand Up @@ -94,7 +95,8 @@ datasource db {
// Generator
generator client {
provider = "prisma-client-dart"
provider = "prisma-client-dart"
previewFeatures = ["interactiveTransactions"]
}
// Data model
Expand Down Expand Up @@ -144,19 +146,19 @@ import 'prisma_client.dart';
final PrismaClient prisma = PrismaClient();
```

Now you can start sending queries via the generated Prisma Client API, here are few sample queries. Note that all Prisma Client queries return plain old `Map<String, dynamic>`.
Now you can start sending queries via the generated Prisma Client API, here are few sample queries.

#### Retrieve all User records from the database

```dart
// Run inside `async` function
final allUsers = await prisma.user.findMany();
final List<User> allUsers = await prisma.user.findMany();
```

#### Filter all Post records that contain "odore"

```dart
final filteredPosts = await prisma.post.findMany(
final List<User> filteredPosts = await prisma.post.findMany(
where: PostFindManyWhereInput(
OR: [
PostFindManyWhereInput(
Expand All @@ -173,19 +175,17 @@ final filteredPosts = await prisma.post.findMany(
#### Create a new User and a new Post record in the same query

```dart
final user = await prisma.user.create(
data: PrismaUnion.zero(
UserCreateInput(
name: 'Odroe',
posts: PostCreateNestedManyWithoutAuthorInput(
create: [
PostCreateWithoutAuthorInput(
title: 'Hello World',
content: 'This is my first post',
published: true,
),
],
),
final User user = await prisma.user.create(
data: UserCreateInput(
name: 'Odroe',
posts: PostCreateNestedManyWithoutAuthorInput(
create: [
PostCreateWithoutAuthorInput(
title: 'Hello World',
content: 'This is my first post',
published: true,
),
],
),
),
);
Expand Down
2 changes: 2 additions & 0 deletions bin/orm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'src/commands/db/db_command.dart';
import 'src/commands/format_command.dart';
import 'src/commands/generate_command.dart';
import 'src/commands/init_command.dart';
import 'src/commands/precache_command.dart';

/// The Prisma CLI executable name.
const String _executableName = r'dart run orm';
Expand All @@ -32,6 +33,7 @@ void main(List<String> args) async {
runner.addCommand(FormatCommand());
runner.addCommand(DbCommand());
runner.addCommand(GenerateCommand());
runner.addCommand(PrecacheCommand());

// Get command result.
final ArgResults results = runner.parse(args);
Expand Down
55 changes: 55 additions & 0 deletions bin/src/commands/precache_command.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'package:args/command_runner.dart';
import 'package:orm/version.dart';

import '../binary_engine/binary_engine.dart';
import '../binary_engine/binary_engine_platform.dart';
import '../binary_engine/binray_engine_type.dart';
import '../utils/ansi_progress.dart';

class PrecacheCommand extends Command {
@override
String get description =>
'Populate the Prisma engines cache of binary artifacts.';

@override
String get name => 'precache';

PrecacheCommand() {
argParser.addMultiOption(
'type',
abbr: 't',
help: 'The engine type to precache.',
valueHelp: 'engine',
allowed: BinaryEngineType.values.map((e) => e.name),
defaultsTo: BinaryEngineType.values.map((e) => e.name),
);
}

Iterable<BinaryEngineType> get types {
final List<String> types = argResults?['type'] as List<String>;
if (types.isEmpty) return BinaryEngineType.values;

return BinaryEngineType.values
.where((element) => types.contains(element.name));
}

@override
void run() async {
for (final BinaryEngineType type in types) {
final BinaryEngine binaryEngine = BinaryEngine(
platform: BinaryEnginePlatform.current,
type: type,
version: binaryVersion,
);

if (!await binaryEngine.hasDownloaded) {
await binaryEngine.download(AnsiProgress.createFutureHandler(
'Download Prisma ${type.name} engine'));
await Future.delayed(Duration(microseconds: 100));
continue;
}

print('Prisma ${type.name} engine is already downloaded.');
}
}
}
1 change: 1 addition & 0 deletions bin/src/generator/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ final List<String> _ignores = [
'constant_identifier_names',
'non_constant_identifier_names',
'depend_on_referenced_packages',
'unused_import',
]..sort();

/// Run Dart client generator
Expand Down
11 changes: 10 additions & 1 deletion bin/src/generator/utils/schema_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ Reference schemaTypeResolver(List<SchemaType> types,
return scalar(uniqueTypes.first, isNullable);
}

// If include `location` is inputObjectTypes. return single inputObjectType
if (uniqueTypes
.any((element) => element.location == FieldLocation.inputObjectTypes)) {
final type = uniqueTypes.firstWhere(
(element) => element.location == FieldLocation.inputObjectTypes);

return scalar(type, isNullable);
}

final Iterable<SchemaType> twoTypes = uniqueTypes.take(2);

// Find is list type.
Expand All @@ -25,7 +34,7 @@ Reference schemaTypeResolver(List<SchemaType> types,
final TypeReference reference = TypeReference((TypeReferenceBuilder updates) {
updates.symbol = 'PrismaUnion';
updates.url = 'package:orm/orm.dart';
updates.types.addAll(types.map((type) => scalar(type)));
updates.types.addAll(twoTypes.map((type) => scalar(type)));
});

if (isNullable) {
Expand Down
3 changes: 2 additions & 1 deletion example/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
Four Prisma examples are available:

- [simple](simple) - A simple Priama example.
- [simple](simple) - A simple Priama example.]
- [Readme example](readme_example) - An example that demonstrates how to use the `readme_example` package. Prisma schema used in [Readme#the-prisma-schema](../README.md#the-prisma-schema).
6 changes: 6 additions & 0 deletions example/readme_example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Files and directories created by pub.
.dart_tool/
.packages

# Conventional directory for build output.
build/
1 change: 1 addition & 0 deletions example/readme_example/.prismarc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL = "postgres://seven@localhost:5432/demo?schema=readme"
3 changes: 3 additions & 0 deletions example/readme_example/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Initial version.
2 changes: 2 additions & 0 deletions example/readme_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
A sample command-line application with an entrypoint in `bin/`, library code
in `lib/`.
30 changes: 30 additions & 0 deletions example/readme_example/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# linter:
# rules:
# - camel_case_types

# analyzer:
# exclude:
# - path/to/excluded/files/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
33 changes: 33 additions & 0 deletions example/readme_example/bin/readme_example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'package:readme_example/readme_example.dart';

void main() async {
final PrismaClient prisma = PrismaClient();

try {
final String email = 'hello@odroe.com';
final User upsertUser = await prisma.user.upsert(
where: UserWhereUniqueInput(email: email),
create: UserCreateInput(email: email),
update: UserUpdateInput(
name: NullableStringFieldUpdateOperationsInput(
set$: PrismaUnion.one(PrismaNull()),
),
),
);

final List<User> nullableUsers = await prisma.user.findMany(
where: UserWhereInput(
name: StringNullableFilter(
equals: PrismaUnion.one(PrismaNull()),
),
),
);

print('Update or create user: \n ${upsertUser.toJson()}');
print('');
print(
'Find nullable users: \n ${nullableUsers.map((e) => e.toJson()).toList()}');
} finally {
await prisma.$disconnect();
}
}
Loading

0 comments on commit 1d0abc3

Please sign in to comment.