flutterfire icon indicating copy to clipboard operation
flutterfire copied to clipboard

🐛 [ODM] Cannot search on Enums (Code Generator does not produce where for type enum)

Open mrorabau opened this issue 2 years ago • 18 comments

Bug report

When having a field with a type enum, the ODM generator automagically produces code to store or retrieve the values (technically as a String), however it does not create the .whereEnumField and .orderEnumField code. It is my assumption this is supposed to work because it will store/retrieve the enums.

Steps to reproduce

Steps to reproduce the behavior:

  1. Create a Model with an (userRef) enum
  2. Create a document using the model to store the enum (usersRef.add(myEnum: testEnum.red))
  3. Attempt to search the model with usersRef.whereMyEnum(isEqualTo: testEnum.red)

Expected behavior

A method .whereMyEnum should be created for each enum field.

Sample project

enum ContentType {
  text,
  image,
  video,
  audio,
}

@JsonSerializable()
class TestUser {
  TestUser({
    required this.name,
    required this.age,
    required this.email,
    this.timestamp = 0,
    this.contentType = ContentType.text,
  }) {
    this.timestamp = Timestamp.now().microsecondsSinceEpoch; //Timestamp.now() nanoseconds.toString();
  }

  String name;
  final String email;
  int timestamp;
  final contentType;

  @Min(0)
  final int age;
}
@Collection<TestUser>('test_users')
final testUsersRef = TestUserCollectionReference();

[...] testUsersRef.whereContentType(isEqualTo: ContentType.text); // Doesn't work


Additional context

As a quick effort, I attempted to add f.isEnumConstant to collection_generator.dart just to see if it would attempt to produce some code, but didn't:

  queryableFields: collectionTargetElement.fields
      .where((f) => f.isPublic)
      .where(
        (f) =>
            f.type.isDartCoreString ||
            f.type.isDartCoreNum ||
            f.type.isDartCoreInt ||
            f.type.isDartCoreDouble ||
            f.type.isDartCoreBool ||
            f.type.isDartCoreList ||
            f.isEnumConstant, // ADDED to Test Enums
        // TODO filter list other than LIst<string|bool|num>
      )
      .toList(),

Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.10.3, on Microsoft Windows [Version 10.0.19044.1586], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0-rc1)              
[√] Chrome - develop for the web                                                           
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.1.1)              
[√] Android Studio (version 2021.1)                                                        
[!] Android Studio                                                                         
    X android-studio-dir = C:\Users\mark\AppData\Local\JetBrains\Toolbox\apps\AndroidStudio
    X Unable to find bundled Java version.                                                 
[√] IntelliJ IDEA Ultimate Edition (version 2021.3)                                        
[√] Connected device (4 available)
[√] HTTP Host Availability

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand
flutter pub deps -- --style=compact
Dart SDK 2.16.1
Flutter SDK 2.10.3
peache_flutter_video 1.0.2+3

dependencies:
- align_positioned 3.0.0 [matrix4_transform flutter]
- animated_text_kit 4.2.1 [flutter characters]
- cached_network_image 3.2.0 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web]
- camera 0.9.4+16 [camera_platform_interface camera_web flutter flutter_plugin_android_lifecycle quiver]
- cloud_firestore 3.1.10 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cloud_firestore_odm 1.0.0-dev.10 [cloud_firestore flutter meta]
- confetti 0.6.0 [flutter vector_math]
- cupertino_icons 1.0.4
- device_info_plus 3.2.2 [flutter device_info_plus_platform_interface device_info_plus_macos device_info_plus_linux device_info_plus_web device_info_plus_windows]
- device_preview 0.7.4 [flutter flutter_localizations provider path_provider device_frame font_awesome_flutter http freezed_annotation json_annotation shared_preferences pedantic path]
- exif 3.1.1 [args collection convert json_annotation sprintf]
- firebase_analytics 8.3.4 [firebase_analytics_platform_interface firebase_analytics_web firebase_core flutter meta]
- firebase_auth 3.3.11 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 1.13.1 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 2.5.3 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_messaging 11.2.11 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_storage 10.2.9 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- flare_flutter 3.0.2 [collection flutter meta]
- flutter 0.0.0 [characters collection material_color_utilities meta typed_data vector_math sky_engine]
- flutter_local_notifications 9.4.0 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_riverpod 2.0.0-dev.4 [collection flutter meta riverpod state_notifier]
- flutter_secure_storage 5.0.2 [meta flutter flutter_secure_storage_linux flutter_secure_storage_macos flutter_secure_storage_platform_interface flutter_secure_storage_web flutter_secure_storage_windows]
- flutter_sms 2.3.2 [flutter flutter_web_plugins plugin_platform_interface url_launcher]
- flutter_svg 0.22.0 [flutter meta path_drawing vector_math xml]
- flutter_tags_x 1.0.0 [flutter]
- flutter_typeahead 3.2.4 [flutter flutter_keyboard_visibility]
- flutter_webrtc 0.7.1 [flutter path_provider]
- fluttermoji 0.2.2 [flutter flutter_svg get shared_preferences]
- fluttertoast 8.0.9 [flutter flutter_web_plugins]
- font_awesome_flutter 10.0.0-beta [flutter lite_graphql]
- get_it 7.2.0 [async collection]
- google_sign_in 5.2.4 [flutter google_sign_in_platform_interface google_sign_in_web]
- http 0.13.4 [async http_parser meta path]
- image_picker 0.8.4+11 [flutter flutter_plugin_android_lifecycle image_picker_for_web image_picker_platform_interface]
- intl 0.17.0 [clock path]
- json_annotation 4.4.0 [meta]
- oauth2 2.0.0 [collection crypto http http_parser]
- package_info_plus 1.4.0 [flutter package_info_plus_platform_interface package_info_plus_linux package_info_plus_macos package_info_plus_windows package_info_plus_web]
- path_provider 2.0.9 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows]
- permission_handler 8.3.0 [flutter meta permission_handler_platform_interface]
- photo_view 0.13.0 [flutter]
- provider 5.0.0 [collection flutter nested]
- qr_flutter 4.0.0 [flutter qr]
- responsive_builder 0.4.2 [flutter]
- share 2.0.4 [meta mime flutter]
- shared_preferences 2.0.13 [flutter shared_preferences_android shared_preferences_ios shared_preferences_linux shared_preferences_macos shared_preferences_platform_interface shared_preferences_web shared_preferences_wind
ows]
- sms_autofill 2.2.0 [pin_input_text_field flutter]
- spincircle_bottom_bar 2.0.0 [flutter]
- telephony 0.1.4 [flutter platform]
- transparent_image 2.0.0
- uni_links 0.5.1 [flutter uni_links_platform_interface uni_links_web]
- universal_platform 1.0.0+1
- video_player 2.3.0 [flutter html video_player_android video_player_avfoundation video_player_platform_interface video_player_web]
- video_thumbnail 0.4.6 [flutter]
- visibility_detector 0.2.2 [flutter]
- xml 5.3.1 [collection meta petitparser]

dev dependencies:
- build_runner 2.1.8 [args async analyzer build build_config build_daemon build_resolvers build_runner_core code_builder collection crypto dart_style frontend_server_client glob graphs http_multi_server io js logging meta
 mime package_config path pool pub_semver pubspec_parse shelf shelf_web_socket stack_trace stream_transform timing watcher web_socket_channel yaml]
- cloud_firestore_odm_generator 1.0.0-dev.10 [analyzer build build_config cloud_firestore_odm collection json_annotation meta recase source_gen]
- flutter_launcher_icons 0.9.2 [args image path yaml]
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher material_color_utilities meta source_span stream_channel string_scanner te
rm_glyph typed_data]
- json_serializable 6.1.5 [analyzer async build build_config collection json_annotation meta path pub_semver pubspec_parse source_gen source_helper]

dependency overrides:
- font_awesome_flutter 10.0.0-beta [flutter lite_graphql]

transitive dependencies:
- _fe_analyzer_shared 31.0.0 [meta]
- analyzer 2.8.0 [_fe_analyzer_shared cli_util collection convert crypto glob meta package_config path pub_semver source_span watcher yaml]
- archive 3.2.2 [crypto path]
- args 2.3.0
- async 2.8.2 [collection meta]
- boolean_selector 2.1.0 [source_span string_scanner]
- build 2.2.1 [analyzer async convert crypto glob logging meta path]
- build_config 1.0.0 [checked_yaml json_annotation path pubspec_parse yaml]
- build_daemon 3.0.1 [built_collection built_value http_multi_server logging path pool shelf shelf_web_socket stream_transform watcher web_socket_channel]
- build_resolvers 2.0.6 [analyzer async build crypto graphs logging path package_config pool pub_semver stream_transform yaml]
- build_runner_core 7.2.3 [async build build_config build_resolvers collection convert crypto glob graphs json_annotation logging meta path package_config pool timing watcher yaml]
- built_collection 5.1.1
- built_value 8.1.4 [built_collection collection fixnum meta]
- cached_network_image_platform_interface 1.0.0 [flutter flutter_cache_manager]
- cached_network_image_web 1.0.1 [flutter flutter_cache_manager cached_network_image_platform_interface]
- camera_platform_interface 2.1.5 [cross_file flutter plugin_platform_interface stream_transform]
- camera_web 0.2.1+3 [camera_platform_interface flutter flutter_web_plugins stream_transform]
- characters 1.2.0
- charcode 1.3.1
- checked_yaml 2.0.1 [json_annotation source_span yaml]
- cli_util 0.3.5 [meta path]
- clock 1.1.0
- cloud_firestore_platform_interface 5.5.1 [collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 2.6.10 [cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js]
- code_builder 4.1.0 [built_collection built_value collection matcher meta]
- collection 1.15.0
- convert 3.0.1 [typed_data]
- cross_file 0.3.2 [flutter js meta]
- crypto 3.0.1 [collection typed_data]
- csslib 0.17.1 [source_span]
- dart_style 2.2.1 [analyzer args path pub_semver source_span]
- dbus 0.7.1 [args ffi meta xml]
- device_frame 0.4.2 [flutter_svg path_drawing freezed_annotation flutter]
- device_info_plus_linux 2.1.1 [device_info_plus_platform_interface file flutter meta]
- device_info_plus_macos 2.2.2 [device_info_plus_platform_interface flutter]
- device_info_plus_platform_interface 2.3.0+1 [flutter meta plugin_platform_interface]
- device_info_plus_web 2.1.0 [device_info_plus_platform_interface flutter_web_plugins flutter]
- device_info_plus_windows 2.1.1 [device_info_plus_platform_interface ffi flutter win32]
- fake_async 1.2.0 [clock collection]
- ffi 1.1.2
- file 6.1.2 [meta path]
- firebase 9.0.2 [http http_parser js]
- firebase_analytics_platform_interface 2.0.1 [flutter meta]
- firebase_analytics_web 0.3.0+1 [firebase firebase_analytics_platform_interface flutter flutter_web_plugins meta]
- firebase_auth_platform_interface 6.2.1 [firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 3.3.9 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser intl js meta]
- firebase_core_platform_interface 4.2.5 [collection flutter meta plugin_platform_interface]
- firebase_core_web 1.6.1 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_crashlytics_platform_interface 3.2.1 [collection firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_platform_interface 3.2.1 [firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 2.2.9 [firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- firebase_storage_platform_interface 4.1.1 [collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.2.10 [async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta]
- fixnum 1.0.0
- flutter_blurhash 0.6.4 [flutter]
- flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid]
- flutter_keyboard_visibility 5.2.0 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_web flutter]
- flutter_keyboard_visibility_platform_interface 2.0.0 [flutter meta plugin_platform_interface]
- flutter_keyboard_visibility_web 2.0.0 [flutter_keyboard_visibility_platform_interface flutter_web_plugins flutter]
- flutter_local_notifications_linux 0.4.2 [flutter flutter_local_notifications_platform_interface dbus path xdg_directories]
- flutter_local_notifications_platform_interface 5.0.0 [flutter plugin_platform_interface]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path typed_data vector_math]
- flutter_plugin_android_lifecycle 2.0.5 [flutter]
- flutter_secure_storage_linux 1.1.0 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_macos 1.1.0 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_platform_interface 1.0.0 [flutter plugin_platform_interface]
- flutter_secure_storage_web 1.0.2 [flutter flutter_web_plugins flutter_secure_storage_platform_interface js]
- flutter_secure_storage_windows 1.1.2 [flutter flutter_secure_storage_platform_interface]
- flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta typed_data vector_math]
- freezed_annotation 0.14.3 [collection json_annotation meta]
- frontend_server_client 2.1.2 [async path]
- get 4.6.1 [flutter]
- glob 2.0.2 [async collection file path string_scanner]
- google_sign_in_platform_interface 2.1.2 [flutter quiver]
- google_sign_in_web 0.10.0+5 [flutter flutter_web_plugins google_sign_in_platform_interface js]
- graphs 2.1.0 [collection]
- html 0.15.0 [csslib source_span]
- http_multi_server 3.2.0 [async]
- http_parser 4.0.0 [charcode collection source_span string_scanner typed_data]
- image 3.1.3 [archive meta xml]
- image_picker_for_web 2.1.6 [flutter flutter_web_plugins image_picker_platform_interface]
- image_picker_platform_interface 2.4.4 [cross_file flutter http plugin_platform_interface]
- io 1.0.3 [meta path string_scanner]
- js 0.6.3
- lite_graphql 0.0.1 [http logger]
- logger 1.1.0
- logging 1.0.2
- matcher 0.12.11 [stack_trace]
- material_color_utilities 0.1.3
- matrix4_transform 2.0.1 [flutter]
- meta 1.7.0
- mime 1.0.1
- nested 1.0.0 [flutter]
- octo_image 1.0.1 [flutter flutter_blurhash]
- package_config 2.0.2 [path]
- package_info_plus_linux 1.0.3 [package_info_plus_platform_interface flutter path]
- package_info_plus_macos 1.3.0 [flutter]
- package_info_plus_platform_interface 1.0.2 [flutter meta plugin_platform_interface]
- package_info_plus_web 1.0.4 [flutter flutter_web_plugins http meta package_info_plus_platform_interface]
- package_info_plus_windows 1.0.4 [package_info_plus_platform_interface ffi flutter win32]
- path 1.8.0
- path_drawing 0.5.1+1 [vector_math meta path_parsing flutter]
- path_parsing 0.2.1 [vector_math meta]
- path_provider_android 2.0.12 [flutter path_provider_platform_interface]
- path_provider_ios 2.0.8 [flutter path_provider_platform_interface]
- path_provider_linux 2.1.5 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_macos 2.0.5 [flutter path_provider_platform_interface]
- path_provider_platform_interface 2.0.3 [flutter platform plugin_platform_interface]
- path_provider_windows 2.0.5 [ffi flutter path path_provider_platform_interface win32]
- pedantic 1.11.1
- permission_handler_platform_interface 3.7.0 [flutter meta plugin_platform_interface]
- petitparser 4.4.0 [meta]
- pin_input_text_field 4.1.2 [flutter]
- platform 3.1.0
- plugin_platform_interface 2.1.2 [meta]
- pool 1.5.0 [async stack_trace]
- process 4.2.4 [file path platform]
- pub_semver 2.1.1 [collection meta]
- pubspec_parse 1.2.0 [checked_yaml collection json_annotation pub_semver yaml]
- qr 2.1.0 [meta]
- quiver 3.0.1+1 [matcher]
- recase 4.0.0
- riverpod 2.0.0-dev.4 [collection meta stack_trace state_notifier]
- rxdart 0.27.3
- shared_preferences_android 2.0.11 [flutter shared_preferences_platform_interface]
- shared_preferences_ios 2.1.0 [flutter shared_preferences_platform_interface]
- shared_preferences_linux 2.1.0 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface]
- shared_preferences_macos 2.0.3 [flutter shared_preferences_platform_interface]
- shared_preferences_platform_interface 2.0.0 [flutter]
- shared_preferences_web 2.0.3 [flutter flutter_web_plugins shared_preferences_platform_interface]
- shared_preferences_windows 2.1.0 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface]
- shelf 1.2.0 [async collection http_parser path stack_trace stream_channel]
- shelf_web_socket 1.0.1 [shelf stream_channel web_socket_channel]
- sky_engine 0.0.99
- source_gen 1.2.1 [analyzer async build dart_style glob meta path source_span yaml]
- source_helper 1.3.1 [analyzer collection source_gen]
- source_span 1.8.1 [collection path term_glyph]
- sprintf 6.0.0
- sqflite 2.0.2 [flutter sqflite_common path]
- sqflite_common 2.2.1 [synchronized path meta]
- stack_trace 1.10.0 [path]
- state_notifier 0.7.2+1 [meta]
- stream_channel 2.1.0 [async]
- stream_transform 2.0.0
- string_scanner 1.1.0 [charcode source_span]
- synchronized 3.0.0
- term_glyph 1.2.0
- test_api 0.4.8 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher]
- timezone 0.8.0 [path]
- timing 1.0.0 [json_annotation]
- typed_data 1.3.0 [collection]
- uni_links_platform_interface 1.0.0 [flutter plugin_platform_interface]
- uni_links_web 0.1.0 [flutter flutter_web_plugins uni_links_platform_interface]
- url_launcher 6.0.20 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- url_launcher_android 6.0.15 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.0.15 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.0 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.0 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.0.5 [flutter plugin_platform_interface]
- url_launcher_web 2.0.9 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.0 [flutter url_launcher_platform_interface]
- uuid 3.0.6 [crypto]
- vector_math 2.1.1
- video_player_android 2.3.1 [flutter video_player_platform_interface]
- video_player_avfoundation 2.3.1 [flutter video_player_platform_interface]
- video_player_platform_interface 5.1.0 [flutter plugin_platform_interface]
- video_player_web 2.0.7 [flutter flutter_web_plugins video_player_platform_interface]
- watcher 1.0.1 [async path]
- web_socket_channel 2.1.0 [async crypto stream_channel]
- win32 2.4.2 [ffi]
- xdg_directories 0.2.0+1 [meta path process]
- yaml 3.1.0 [collection source_span string_scanner]


mrorabau avatar Mar 25 '22 22:03 mrorabau

Let me clarify. Adding f.isEnumConstant, did produce code, but ended up breaking.

It seems that adding it to queryableFields causes this:

   Future<void> set(TestUser value) {
    return reference.set(value);
  }

to fail. Specifically it gets down to firestore_message_codec.dart writeValue(WriteBuffer buffer, dynamic value) where it can't find an isEnumConstant, and then calls super to package:flutter/src/services/message_codecs.dart which also lacks that type.

E/flutter ( 5802): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument: Instance of 'ContentType'
E/flutter ( 5802): #0      StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:426:7)
E/flutter ( 5802): #1      FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:114:13)
E/flutter ( 5802): #2      StandardMessageCodec.writeValue.<anonymous closure> (package:flutter/src/services/message_codecs.dart:423:9)
E/flutter ( 5802): #3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter ( 5802): #4      StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:421:13)
E/flutter ( 5802): #5      FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:114:13)
E/flutter ( 5802): #6      StandardMessageCodec.writeValue.<anonymous closure> (package:flutter/src/services/message_codecs.dart:423:9)
E/flutter ( 5802): #7      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
E/flutter ( 5802): #8      StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:421:13)
E/flutter ( 5802): #9      FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:114:13)
E/flutter ( 5802): #10     StandardMethodCodec.encodeMethodCall (package:flutter/src/services/message_codecs.dart:561:18)
E/flutter ( 5802): #11     MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:169:13)
E/flutter ( 5802): #12     MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:350:12)
E/flutter ( 5802): #13     MethodChannelDocumentReference.set (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:31:52)
E/flutter ( 5802): #14     _JsonDocumentReference.set (package:cloud_firestore/src/document_reference.dart:166:22)
E/flutter ( 5802): #15     _WithConverterDocumentReference.set (package:cloud_firestore/src/document_reference.dart:263:39)
E/flutter ( 5802): #16     _$TestUserDocumentReference.set (package:peache_flutter_video/util/DB/stories_model.g.dart:186:22)
E/flutter ( 5802): #17     testFirebaseData (package:peache_flutter_video/util/DB/db_helpers.dart:192:30)
E/flutter ( 5802): <asynchronous suspension>
E/flutter ( 5802): 

mrorabau avatar Mar 27 '22 14:03 mrorabau

/cc @rrousselGit

darshankawar avatar Mar 28 '22 12:03 darshankawar

Update: So adding the f.isEnumConstant above, and then modifying the generated where code to this seems to work (could use more testing):

TestUserQuery whereContentType({
    ContentType? isEqualTo,
    ContentType? isNotEqualTo,
    ContentType? isLessThan,
    ContentType? isLessThanOrEqualTo,
    ContentType? isGreaterThan,
    ContentType? isGreaterThanOrEqualTo,
    bool? isNull,
    List<ContentType>? whereIn,
    List<ContentType>? whereNotIn,
  }) {
    List<String>? _whereInList;
    whereIn?.forEach((e) { _whereInList?.add(e.name); });
    List<String>? _whereNotInList;
    whereNotIn?.forEach((e) { _whereNotInList?.add(e.name); });

    return _$TestUserQuery(
      reference.where(
        'contentType',
        isEqualTo: isEqualTo?.name,
        isNotEqualTo: isNotEqualTo?.name,
        isLessThan: isLessThan?.name,
        isLessThanOrEqualTo: isLessThanOrEqualTo?.name,
        isGreaterThan: isGreaterThan?.name,
        isGreaterThanOrEqualTo: isGreaterThanOrEqualTo?.name,
        isNull: isNull,
        whereIn: _whereInList,
        whereNotIn: _whereNotInList,
      ),
      _collection,
    );
  }

I can look into modifying the code generator (query_reference.dart?) to see if this can be modified, but code generation in flutter/dart is a bit new to me.

mrorabau avatar Mar 30 '22 20:03 mrorabau

Enums are a bit difficult to support at the moment, because the ODM is unaware of how they are serialized

We can start with supporting only the Enum.value.toString(). But supporting cases like:

enum MyEnum {
  @JsonValue('actually_some_value')
  someValue,
}

will require a bit more work

rrousselGit avatar Apr 05 '22 10:04 rrousselGit

The PR I came up with supported only Enum.name, perhaps Enum.value.toString(). I do think that supporting this PR will be a 80%+ scenario. I wasn't aware that you already supported @JsonValue elsewhere. I know that was requested, but didn't see it in the docs.

My thoughts are to support the basic Enum for now, and add to the docs that supporting more complicated Enums/@JsonValues are being considered for the future, but not available currently.

The reason why I considered this a bug and not an enhancement is because you can save and retrieve Enums already -- it is just searching/orderby.

mrorabau avatar Apr 06 '22 17:04 mrorabau

Enums are a bit difficult to support at the moment, because the ODM is unaware of how they are serialized

We can start with supporting only the Enum.value.toString(). But supporting cases like:

enum MyEnum {
  @JsonValue('actually_some_value')
  someValue,
}

will require a bit more work

Now with Dart 2.17, it becomes simpler, doesn't it?

Hinten avatar May 16 '22 15:05 Hinten

@Hinten @rrousselGit

Now with Dart 2.17, it becomes simpler, doesn't it?

Sort of. I've been looking at that, but part of the issue is de-serializing it. Unless I'm missing something (and probably am), the toString() override is unidirectional. For example:

enum MyEnum {
  final String myEnumVal;
  const MyEnum(this.myEnumVal);

  foo("bar"),
  foo2("bar2"),

  @override
  String toString() => "Let's go to the $myEnumVal";
}

This (quickly written and untested) code would store something like "Let's go to the bar." If we tried to retrieve that and set it back to an enum we wouldn't know that it should be "foo."

The PR I submitted attempts to use the enum name (foo/foo2) for the moment. It is true that if we support @JsonValue('something'), as long as it was unique it should de-serialize back into what we want.

mrorabau avatar May 16 '22 16:05 mrorabau

toString assumes that the enum is encoded into a String. But sometimes they are encoded into integers or other values

Rather, it could be a matter of adding a fromJson/toJson to your enums

rrousselGit avatar May 16 '22 17:05 rrousselGit

@rrousselGit

toString assumes that the enum is encoded into a String. But sometimes they are encoded into integers or other values

Rather, it could be a matter of adding a fromJson/toJson to your enums

All excellent points. The current code (before my PR) doesn't recognize enums, so it doesn't generate the search/where code. I think that part has to be added no matter what. the fromJson/toJson could manually handle the serialization.

mrorabau avatar May 16 '22 17:05 mrorabau

This can work:

enum Soccer {
  maradona(1),
  pele(2),
  messi(3),
  ronaldo(4),
  cristianoRonaldo(5);

  final int value;

  const Soccer(this.value);

  factory Soccer.getEnum(int _value){
    for (var element in Soccer.values) {
      if (element.value == _value) {
        return element;
      }
    }
    throw Exception('$_value is invalid.');
  }

  @override
  String toString() {
    return name;
  }
}

void main() async {
  print(Soccer.pele.toString());
  print(Soccer.pele.value == 1);
  print(Soccer.pele.value > Soccer.maradona.value);
}

enums now have a default name attribute;

Hinten avatar May 16 '22 19:05 Hinten

Actually, we doesnt even have to override the toString method, one can just use enum.name in the code.

Hinten avatar May 16 '22 19:05 Hinten

The PR I submitted attempts to use the enum name (foo/foo2) for the moment. Actually, we doesnt even have to override the toString method, one can just use enum.name in the code.

@Hinten That is what I did in my current PR. I used enum.name (see above).

mrorabau avatar May 16 '22 20:05 mrorabau

Any updates?

For now, we'll use this ugly workaround:

final query = await usersRef
  .whereFieldPath(
    FieldPath.fromString("versionEnum"),
    isEqualTo: Version.v1.name,
  )
  .get();

ciriousjoker avatar Jul 20 '22 23:07 ciriousjoker

We can start with supporting only the Enum.value.toString()

May be this is good to start with.

Purus avatar Oct 04 '22 06:10 Purus

@Purus @ciriousjoker

I'm sorry, @rrousselGit provided feedback for me to get the submission done, however I got severely bogged down with other priorities. I will attempt to work on it in the next few days to update the PR with @rrousselGit request.

Thanks for everyone's patience.

mrorabau avatar Oct 09 '22 15:10 mrorabau

The PR I came up with supported only Enum.name, perhaps Enum.value.toString(). I do think that supporting this will be a 80%+ scenario. I wasn't aware that you supported @JsonValue already. I know that was requested, but didn't see it in the docs.

My thoughts are to support the basic Enum for now, and add that supporting more complicated Enums are being considered for the future, but not available currently.

-mark

On Tue, Apr 5, 2022 at 6:47 AM Remi Rousselet @.***> wrote:

Enums are a bit difficult to support at the moment, because the ODM is unaware of how they are serialized

We can start with supporting only the Enum.value.toString(). But supporting cases like:

enum MyEnum { @JsonValue('actually_some_value') someValue, }

will require a bit more work

— Reply to this email directly, view it on GitHub https://github.com/firebase/flutterfire/issues/8338#issuecomment-1088549470, or unsubscribe https://github.com/notifications/unsubscribe-auth/AANWRAZBTCIGRZV5MWV7JHLVDQK5DANCNFSM5RVON57Q . You are receiving this because you authored the thread.Message ID: @.***>

mrorabau avatar Oct 11 '22 07:10 mrorabau

Hello all! Is there any update on generated where clauses with enums? I'm having trouble finding examples of how it works on Google/examples on here. Although I made a custom converter based off of lib/cloud_firestore_odm.dart to interpret an enum, it seems to generate code where clauses/add it to the update function for everything other than the enum I have inside a given model.

Sample (hopefully close to minimum) code:

enum TestEnum {
  initialState,
  interimState,
  finishedState,
}

/// A [JsonConverter] that adds support for [TestEnum] objects within ODM models.
class FirestoreTestEnumConverter extends JsonConverter<TestEnum, TestEnum> {
  const FirestoreTestEnumConverter();

  @override
  TestEnum fromJson(TestEnum json) => json;

  @override
  TestEnum toJson(TestEnum object) => object;
}

// there's probably a better way to do this, but i was unsure how
const List<JsonConverter<Object?, Object?>> customConverters = [
  FirestoreDateTimeConverter(),
  FirestoreTimestampConverter(),
  FirestoreGeoPointConverter(),
  FirestoreDocumentReferenceConverter(),
  FirestoreTestEnumConverter()
];

const JsonSerializable firestoreSerializable = JsonSerializable(
  converters: customConverters,
  // The following values could alternatively be set inside your `build.yaml`
  explicitToJson: true,
  createFieldMap: true,
);

@firestoreSerializable
class TestModel {
  const TestModel({
    this.testEnum = TestEnum.initialState,
  });

  final TestEnum testEnum;
}

I'm hoping I'm just missing something like an annotation in the code or some documentation somewhere about it. Appreciate any thoughts on this!

Edit: As an addendum, I've spent the last bit trying to modify cloud_firestore_odm to try and make enums work. I now have code generating where clauses, but they don't work properly and produce a Invalid argument: Instance of 'TestEnum' error. Even if I implement a custom JSONConvertor, and append it to the default firestoreJsonConverters for use in firestoreSerializable, it doesn't handle the whereTestEnum clause correctly that way either. Curiously, if I modify the generated code and convert the TestEnum to a string or list of strings (the JSONified version, basically) when the argument is given to the $*query function, the whereTestEnum clause works perfectly.

ajmcgrail avatar May 18 '23 16:05 ajmcgrail

Poking @rrousselGit, do you have any thoughts on why Enum serialization wouldn't be handled in Enum where clauses? I've spent the better part of two days looking into the generated code, but I can't figure out why Timestamps and Geopoints are covered, but not my own custom enum type when it comes to querying. If for example, I remove the JsonConverter for timestamps from the serializer, I actually receive build errors (from build_runner) about the fact that it won't be able to correctly serialize the type. But whether or not I do or do not provide a serializer for an enum, this error never pops up. Probably because the built in serializer 'knows' how to correctly serialize and map basic enums, but I'm very lost as to why I would receive invalid argument errors when JSON serialization methods are explicitly provided. It doesn't even seem to use the JSON serialization when using the whereTestEnum clause, or at least it doesn't correctly do debugPrint statements for whatever that's worth.

Anyways, I'm hoping you might have a solution to this problem now that it's a couple months later.

ajmcgrail avatar May 19 '23 20:05 ajmcgrail