diff --git a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline.dart b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline.dart index 14074ec9ab02..3b8d6c636686 100644 --- a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline.dart +++ b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline.dart @@ -65,7 +65,10 @@ class Pipeline { /// ``` Future execute({ExecuteOptions? options}) async { final optionsMap = options != null - ? {'indexMode': options.indexMode.name} + ? { + 'indexMode': options.indexMode.name, + if (options.atomic) 'atomic': true, + } : null; final platformSnapshot = await _delegate.execute(options: optionsMap); return _convertPlatformSnapshot(platformSnapshot); @@ -808,4 +811,77 @@ class Pipeline { final stage = _WhereStage(expression); return Pipeline._(_firestore, _delegate.addStage(stage.toMap())); } + + /// Deletes each input document at its `__name__` path. + /// + /// Example: + /// ```dart + /// firestore + /// .pipeline() + /// .collection('books') + /// .where(Expression.field('genre').equal('Science Fiction')) + /// .delete(); + /// ``` + Pipeline delete() { + final stage = _DeleteStage(); + return Pipeline._(_firestore, _delegate.addStage(stage.toMap())); + } + + /// Updates each input document at its `__name__` path. + /// + /// [transformedFields] are aliased expressions applied before the write. + /// When omitted, each input document is written back from its current + /// fields. This stage does not create missing documents. + /// + /// Example: + /// ```dart + /// firestore.pipeline().collection('books').update([ + /// Expression.field('rating').as('score'), + /// ]); + /// ``` + Pipeline update([List transformedFields = const []]) { + final stage = _UpdateStage(transformedFields); + return Pipeline._(_firestore, _delegate.addStage(stage.toMap())); + } + + /// Inserts each input document. + /// + /// The write fails if a document already exists at the target path. The + /// target is the input document's `__name__` when [collectionPath] and + /// [documentId] are both omitted. [collectionPath] writes into that + /// collection, reusing the input document id or generating one. + /// [documentId] is evaluated for each document: a field path is + /// [Expression.field], and a fixed id is [Expression.constant]. + Pipeline insert({String? collectionPath, Expression? documentId}) { + _checkCollectionPath(collectionPath); + final stage = _InsertStage(collectionPath, documentId); + return Pipeline._(_firestore, _delegate.addStage(stage.toMap())); + } + + /// Inserts each input document, or replaces it when the target already exists. + /// + /// An existing document is replaced entirely. Fields that are not in the + /// written document are removed. [additionalFields] are aliased expressions + /// merged onto each input document before the write. See [insert] for how + /// [collectionPath] and [documentId] choose the target path. + Pipeline upsert({ + String? collectionPath, + Expression? documentId, + List additionalFields = const [], + }) { + _checkCollectionPath(collectionPath); + final stage = _UpsertStage(collectionPath, documentId, additionalFields); + return Pipeline._(_firestore, _delegate.addStage(stage.toMap())); + } +} + +void _checkCollectionPath(String? collectionPath) { + if (collectionPath == null) { + return; + } + if (collectionPath.isEmpty) { + throw ArgumentError('A collection path must be a non-empty string.'); + } else if (collectionPath.contains('//')) { + throw ArgumentError('A collection path must not contain "//".'); + } } diff --git a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_execute_options.dart b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_execute_options.dart index 191545f1651e..20bd0aea9859 100644 --- a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_execute_options.dart +++ b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_execute_options.dart @@ -12,7 +12,18 @@ enum IndexMode { /// Options for executing a pipeline class ExecuteOptions { + /// Which indexes the backend may use. final IndexMode indexMode; - const ExecuteOptions({this.indexMode = IndexMode.recommended}); + /// When true, data-manipulation stages commit in one transaction. + /// + /// When false, each document write is applied on its own and a pipeline + /// can partially succeed. Some writes, such as [PipelineSource.literals] + /// followed by [Pipeline.upsert], are rejected unless this is true. + final bool atomic; + + const ExecuteOptions({ + this.indexMode = IndexMode.recommended, + this.atomic = false, + }); } diff --git a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_source.dart b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_source.dart index 69d4be991a5d..47356370f06b 100644 --- a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_source.dart +++ b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_source.dart @@ -64,4 +64,27 @@ class PipelineSource { final delegate = _firestore._delegate.pipeline([stage.toMap()]); return Pipeline._(_firestore, delegate); } + + /// Creates a pipeline from literal documents. + /// + /// Each map is one document. A field value may be a plain value or an + /// [Expression]. Expressions are only supported as top-level fields. + /// Nested maps and lists are plain values. + /// + /// Example: + /// ```dart + /// firestore.pipeline().literals([ + /// {'name': 'Alice', 'score': 50}, + /// {'name': 'Bob', 'score': Expression.constant(70)}, + /// ]); + /// ``` + Pipeline literals(List> documents) { + if (documents.isEmpty) { + throw ArgumentError('Documents list must not be empty.'); + } + + final stage = _LiteralsPipelineStage(documents); + final delegate = _firestore._delegate.pipeline([stage.toMap()]); + return Pipeline._(_firestore, delegate); + } } diff --git a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_stage.dart b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_stage.dart index 7c9ccb30473f..3451a0967b40 100644 --- a/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_stage.dart +++ b/packages/cloud_firestore/cloud_firestore/lib/src/pipeline_stage.dart @@ -385,6 +385,165 @@ final class _UnionStage extends PipelineStage { } } +/// Stage that deletes each input document. +final class _DeleteStage extends PipelineStage { + @override + String get name => 'delete'; + + @override + Map toMap() { + return {'stage': name, 'args': {}}; + } +} + +/// Stage that updates each input document. +final class _UpdateStage extends PipelineStage { + final List transformedFields; + + _UpdateStage(this.transformedFields); + + @override + String get name => 'update'; + + @override + Map toMap() { + return { + 'stage': name, + 'args': { + 'expressions': transformedFields.map((field) => field.toMap()).toList(), + }, + }; + } +} + +/// Stage that inserts each input document. +final class _InsertStage extends PipelineStage { + final String? collectionPath; + final Expression? documentId; + + _InsertStage(this.collectionPath, this.documentId); + + @override + String get name => 'insert'; + + @override + Map toMap() { + return { + 'stage': name, + 'args': _writeTargetArgs(collectionPath, documentId), + }; + } +} + +/// Stage that inserts or replaces each input document. +final class _UpsertStage extends PipelineStage { + final String? collectionPath; + final Expression? documentId; + final List additionalFields; + + _UpsertStage(this.collectionPath, this.documentId, this.additionalFields); + + @override + String get name => 'upsert'; + + @override + Map toMap() { + final args = _writeTargetArgs(collectionPath, documentId); + if (additionalFields.isNotEmpty) { + args['additional_fields'] = additionalFields + .map((field) => field.toMap()) + .toList(); + } + return {'stage': name, 'args': args}; + } +} + +Map _writeTargetArgs( + String? collectionPath, + Expression? documentId, +) { + final args = {}; + if (collectionPath != null) { + args['collection'] = collectionPath; + } + if (documentId != null) { + args['document_id'] = documentId.toMap(); + } + return args; +} + +/// Stage representing literal documents as a pipeline source. +final class _LiteralsPipelineStage extends PipelineStage { + final List> documents; + + _LiteralsPipelineStage(this.documents); + + @override + String get name => 'literals'; + + @override + Map toMap() { + return { + 'stage': name, + 'args': {'documents': documents.map(_encodeLiteralDocument).toList()}, + }; + } +} + +Map _encodeLiteralDocument(Map document) { + return document.map( + (key, value) => MapEntry(key, _encodeLiteralField(value)), + ); +} + +Map _encodeLiteralField(Object? value) { + if (value is Expression) { + return {'kind': 'expression', 'expression': value.toMap()}; + } + if (value is DocumentReference) { + return {'kind': 'expression', 'expression': Constant(value).toMap()}; + } + return {'kind': 'value', 'value': _encodeLiteralValue(value)}; +} + +Object? _encodeLiteralValue(Object? value) { + if (value is Expression) { + throw ArgumentError( + 'literals() only supports Expression values as top-level document fields.', + ); + } + if (value is DocumentReference) { + throw ArgumentError( + 'literals() only supports DocumentReference values as top-level ' + 'document fields.', + ); + } + if (value == null || + value is String || + value is num || + value is bool || + value is DateTime || + value is Timestamp || + value is GeoPoint || + value is Blob || + value is VectorValue) { + return value; + } + if (value is Map) { + return value.map( + (key, nested) => MapEntry(key.toString(), _encodeLiteralValue(nested)), + ); + } + if (value is List) { + return value.map(_encodeLiteralValue).toList(); + } + throw ArgumentError( + 'literals() value must be null, String, num, bool, DateTime, Timestamp, ' + 'GeoPoint, Blob, VectorValue, List, Map, or a top-level Expression. ' + 'Got: ${value.runtimeType}', + ); +} + /// Stage for filtering documents final class _WhereStage extends PipelineStage { final BooleanExpression expression; diff --git a/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_live_test.dart b/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_live_test.dart index b361d17bbb45..b4fc69ed160b 100644 --- a/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_live_test.dart +++ b/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_live_test.dart @@ -23,6 +23,7 @@ import 'pipeline_search_e2e.dart'; import 'pipeline_seed.dart'; import 'pipeline_select_e2e.dart'; import 'pipeline_unnest_union_e2e.dart'; +import 'pipeline_writes_e2e.dart'; void main() { final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -64,5 +65,6 @@ void main() { runPipelineFindNearestTests(); runPipelineSearchTests(); runPipelineExpressionsTests(); + runPipelineWriteTests(); }); } diff --git a/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_writes_e2e.dart b/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_writes_e2e.dart new file mode 100644 index 000000000000..0102cd1d0718 --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore/pipeline_example/integration_test/pipeline/pipeline_writes_e2e.dart @@ -0,0 +1,85 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void runPipelineWriteTests() { + group('Pipeline writes', () { + late FirebaseFirestore firestore; + + setUpAll(() { + firestore = FirebaseFirestore.instanceFor( + app: Firebase.app(), + databaseId: 'firestore-pipeline-test', + ); + }); + + test('literals upsert, update, insert, and delete round-trip', () async { + final collection = + 'pipeline-writes-${DateTime.now().microsecondsSinceEpoch}'; + + Future?> read(String id) async { + final snapshot = await firestore + .collection(collection) + .doc(id) + .get(const GetOptions(source: Source.server)); + return snapshot.data(); + } + + try { + await firestore + .pipeline() + .literals([ + { + 'name': 'ada', + 'score': Expression.constant(1), + 'tags': ['a', 'b'], + }, + ]) + .upsert( + collectionPath: collection, + documentId: Expression.constant('ada'), + ) + .execute(options: const ExecuteOptions(atomic: true)); + + expect(await read('ada'), { + 'name': 'ada', + 'score': 1, + 'tags': ['a', 'b'], + }); + + await firestore.pipeline().collection(collection).update([ + Expression.constant(2).as('score'), + ]).execute(); + + final updated = await read('ada'); + expect(updated?['name'], 'ada'); + expect(updated?['score'], 2); + + await firestore + .pipeline() + .literals([ + {'name': 'grace', 'score': Expression.constant(3)}, + ]) + .insert( + collectionPath: collection, + documentId: Expression.constant('grace'), + ) + .execute(options: const ExecuteOptions(atomic: true)); + + expect(await read('grace'), {'name': 'grace', 'score': 3}); + + await firestore.pipeline().collection(collection).delete().execute(); + + expect(await read('ada'), isNull); + expect(await read('grace'), isNull); + } finally { + await firestore.pipeline().collection(collection).delete().execute(); + } + }); + }, skip: kIsWeb ? false : 'Pipeline writes run on web.'); +} diff --git a/packages/cloud_firestore/cloud_firestore/test/pipeline_execute_options_test.dart b/packages/cloud_firestore/cloud_firestore/test/pipeline_execute_options_test.dart index cdd91f7b32c7..a3b153592a91 100644 --- a/packages/cloud_firestore/cloud_firestore/test/pipeline_execute_options_test.dart +++ b/packages/cloud_firestore/cloud_firestore/test/pipeline_execute_options_test.dart @@ -3,8 +3,12 @@ // BSD-style license that can be found in the LICENSE file. import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart'; +import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_test/flutter_test.dart'; +import './mock.dart'; + void main() { group('IndexMode', () { test('recommended has expected name', () { @@ -17,5 +21,121 @@ void main() { const options = ExecuteOptions(); expect(options.indexMode, IndexMode.recommended); }); + + test('atomic defaults to false', () { + const options = ExecuteOptions(); + expect(options.atomic, isFalse); + }); + + test('atomic can be enabled', () { + const options = ExecuteOptions(atomic: true); + expect(options.atomic, isTrue); + }); }); + + group('Pipeline.execute options', () { + final recorder = _ExecuteRecorder(); + + setUpAll(() async { + setupCloudFirestoreMocks(); + await Firebase.initializeApp(); + FirebaseFirestorePlatform.instance = _RecordingFirestore(recorder); + }); + + setUp(recorder.reset); + + test('includes atomic only when it is enabled', () async { + await expectLater( + FirebaseFirestore.instance + .pipeline() + .collection('users') + .execute(options: const ExecuteOptions(atomic: true)), + throwsA(isA()), + ); + + expect(recorder.called, isTrue); + expect(recorder.options, {'indexMode': 'recommended', 'atomic': true}); + }); + + test('omits atomic when ExecuteOptions uses the default', () async { + await expectLater( + FirebaseFirestore.instance + .pipeline() + .collection('users') + .execute(options: const ExecuteOptions()), + throwsA(isA()), + ); + + expect(recorder.called, isTrue); + expect(recorder.options, {'indexMode': 'recommended'}); + }); + + test('passes null when execute is called without options', () async { + await expectLater( + FirebaseFirestore.instance.pipeline().collection('users').execute(), + throwsA(isA()), + ); + + expect(recorder.called, isTrue); + expect(recorder.options, isNull); + }); + }); +} + +class _ExecuteRecorder { + Map? options; + bool called = false; + + void reset() { + options = null; + called = false; + } +} + +class _RecordingFirestore extends FirebaseFirestorePlatform { + _RecordingFirestore(this.recorder) + : super(appInstance: Firebase.app(), databaseChoice: '(default)'); + + final _ExecuteRecorder recorder; + + @override + FirebaseFirestorePlatform delegateFor({ + required FirebaseApp app, + required String databaseId, + }) { + return this; + } + + @override + PipelinePlatform pipeline(List> initialStages) { + return _RecordingPipeline(this, initialStages, recorder); + } +} + +class _RecordingPipeline extends PipelinePlatform { + _RecordingPipeline( + FirebaseFirestorePlatform firestore, + List>? stages, + this.recorder, + ) : super(firestore, stages); + + final _ExecuteRecorder recorder; + + @override + PipelinePlatform addStage(Map serializedStage) { + return _RecordingPipeline(firestore, >[ + ...stages, + serializedStage, + ], recorder); + } + + @override + Future execute({Map? options}) { + recorder + ..called = true + ..options = options; + return Future.error( + UnsupportedError('execute options recorded'), + ); + } } diff --git a/packages/cloud_firestore/cloud_firestore/test/pipeline_source_test.dart b/packages/cloud_firestore/cloud_firestore/test/pipeline_source_test.dart index e5c64f11b5ab..41f9347e2236 100644 --- a/packages/cloud_firestore/cloud_firestore/test/pipeline_source_test.dart +++ b/packages/cloud_firestore/cloud_firestore/test/pipeline_source_test.dart @@ -131,6 +131,52 @@ void main() { }); }); + group('literals()', () { + test('serializes a plain value and an expression', () { + final pipeline = firestore.pipeline().literals([ + { + 'name': 'Alice', + 'score': Expression.constant(50), + 'address': {'city': 'Accra'}, + }, + ]); + expect(pipeline.stages, hasLength(1)); + expect(pipeline.stages.first['stage'], 'literals'); + final documents = + pipeline.stages.first['args']['documents'] as List; + expect(documents, hasLength(1)); + expect(documents.first, { + 'name': {'kind': 'value', 'value': 'Alice'}, + 'score': { + 'kind': 'expression', + 'expression': { + 'name': 'constant', + 'args': {'value': 50}, + }, + }, + 'address': { + 'kind': 'value', + 'value': {'city': 'Accra'}, + }, + }); + }); + + test('throws on an empty list', () { + expect(() => firestore.pipeline().literals([]), throwsArgumentError); + }); + + test('throws when an expression is nested', () { + expect( + () => firestore.pipeline().literals([ + { + 'address': {'city': Expression.constant('Accra')}, + }, + ]), + throwsArgumentError, + ); + }); + }); + group('chaining from source', () { test('returned pipeline accepts stage methods', () { final pipeline = firestore diff --git a/packages/cloud_firestore/cloud_firestore/test/pipeline_stage_test.dart b/packages/cloud_firestore/cloud_firestore/test/pipeline_stage_test.dart index 1809efa2ec0c..5034861500d6 100644 --- a/packages/cloud_firestore/cloud_firestore/test/pipeline_stage_test.dart +++ b/packages/cloud_firestore/cloud_firestore/test/pipeline_stage_test.dart @@ -574,5 +574,97 @@ void main() { expect(pipeline.stages[4]['stage'], 'offset'); }); }); + + group('data manipulation stages', () { + test('serializes delete with empty args', () { + final pipeline = firestore.pipeline().collection('books').delete(); + expect(pipeline.stages.last, { + 'stage': 'delete', + 'args': {}, + }); + }); + + test('serializes update with no transformed fields', () { + final pipeline = firestore.pipeline().collection('books').update(); + expect(pipeline.stages.last, { + 'stage': 'update', + 'args': {'expressions': >[]}, + }); + }); + + test('serializes update transformed fields', () { + final pipeline = firestore.pipeline().collection('books').update([ + Expression.field('rating').as('score'), + ]); + expect(pipeline.stages.last['stage'], 'update'); + expect(pipeline.stages.last['args']['expressions'], [ + { + 'name': 'alias', + 'args': { + 'alias': 'score', + 'expression': { + 'name': 'field', + 'args': {'field': 'rating'}, + }, + }, + }, + ]); + }); + + test( + 'serializes insert with a collection and document id expression', + () { + final pipeline = firestore + .pipeline() + .literals([ + {'title': 'Dune'}, + ]) + .insert( + collectionPath: 'books', + documentId: Expression.constant('dune'), + ); + expect(pipeline.stages.last, { + 'stage': 'insert', + 'args': { + 'collection': 'books', + 'document_id': { + 'name': 'constant', + 'args': {'value': 'dune'}, + }, + }, + }); + }, + ); + + test('serializes upsert additional fields', () { + final pipeline = firestore + .pipeline() + .collection('books') + .upsert(additionalFields: [Expression.field('title').as('name')]); + expect(pipeline.stages.last['stage'], 'upsert'); + expect(pipeline.stages.last['args']['additional_fields'], [ + { + 'name': 'alias', + 'args': { + 'alias': 'name', + 'expression': { + 'name': 'field', + 'args': {'field': 'title'}, + }, + }, + }, + ]); + }); + + test('throws when insert collection path is empty', () { + expect( + () => firestore + .pipeline() + .collection('books') + .insert(collectionPath: ''), + throwsArgumentError, + ); + }); + }); }); } diff --git a/packages/cloud_firestore/cloud_firestore_web/lib/cloud_firestore_web.dart b/packages/cloud_firestore/cloud_firestore_web/lib/cloud_firestore_web.dart index ce893baae41a..ca78c1a6e4a3 100644 --- a/packages/cloud_firestore/cloud_firestore_web/lib/cloud_firestore_web.dart +++ b/packages/cloud_firestore/cloud_firestore_web/lib/cloud_firestore_web.dart @@ -318,11 +318,16 @@ class FirebaseFirestoreWeb extends FirebaseFirestorePlatform { final dartPipeline = firestore_interop.Pipeline.getInstance(jsPipeline); return convertWebExceptions(() async { - String? executeOptions; + String? indexMode; + bool? atomic; if (options != null) { - executeOptions = options['indexMode'] as String; + indexMode = options['indexMode'] as String?; + atomic = options['atomic'] as bool?; } - final snapshot = await dartPipeline.execute(executeOptions); + final snapshot = await dartPipeline.execute( + indexMode: indexMode, + atomic: atomic, + ); final results = snapshot.results .map((r) => PipelineResultWeb(this, _delegate, r.jsObject)) diff --git a/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore.dart b/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore.dart index 7e9aacae8b98..1fb83796f017 100644 --- a/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore.dart +++ b/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore.dart @@ -1308,10 +1308,13 @@ class Pipeline extends JsObjectWrapper { : super.fromJsObject(jsObject); /// Runs this pipeline using the global JS SDK execute function. - Future execute(String? executeOptions) async { + Future execute({String? indexMode, bool? atomic}) async { final executeOptionsJs = firestore_interop.PipelineExecuteOptionsJsImpl(); - if (executeOptions != null) { - executeOptionsJs.indexMode = executeOptions.toJS; + if (indexMode != null) { + executeOptionsJs.indexMode = indexMode.toJS; + } + if (atomic ?? false) { + executeOptionsJs.atomic = true.toJS; } executeOptionsJs.pipeline = jsObject as JSAny; final snapshot = await firestore_interop.pipelines diff --git a/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore_interop.dart b/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore_interop.dart index e90a335aa094..baab4b535618 100644 --- a/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore_interop.dart +++ b/packages/cloud_firestore/cloud_firestore_web/lib/src/interop/firestore_interop.dart @@ -1260,6 +1260,9 @@ extension type PipelineSourceJsImpl._(JSObject _) implements JSObject { /// Sets the pipeline source to the given document paths or references. external PipelineJsImpl documents(JSArray docs); + + /// Sets the pipeline source to the given literal documents. + external PipelineJsImpl literals(JSAny documents); } /// Pipeline returned by PipelineSource methods; chain stages and call execute(). @@ -1280,6 +1283,10 @@ extension type PipelineJsImpl._(JSObject _) implements JSObject { external PipelineJsImpl findNearest(JSAny options); external PipelineJsImpl search(JSAny options); external PipelineJsImpl union(JSAny otherOrOptions); + external PipelineJsImpl delete(JSAny options); + external PipelineJsImpl update(JSAny options); + external PipelineJsImpl insert(JSAny options); + external PipelineJsImpl upsert(JSAny options); external PipelineJsImpl rawStage( JSString name, JSArray params, [ @@ -1404,5 +1411,38 @@ extension type PipelineExecuteOptionsJsImpl._(JSObject _) implements JSObject { // ignore: avoid_setters_without_getters external set indexMode(JSString value); // ignore: avoid_setters_without_getters + external set atomic(JSBoolean value); + // ignore: avoid_setters_without_getters external set pipeline(JSAny value); } + +extension type DeleteStageOptionsJsImpl._(JSObject _) implements JSObject { + DeleteStageOptionsJsImpl() : this._(JSObject.new()); +} + +extension type UpdateStageOptionsJsImpl._(JSObject _) implements JSObject { + UpdateStageOptionsJsImpl() : this._(JSObject.new()); + + // ignore: avoid_setters_without_getters + external set transformedFields(JSAny value); +} + +extension type InsertStageOptionsJsImpl._(JSObject _) implements JSObject { + InsertStageOptionsJsImpl() : this._(JSObject.new()); + + // ignore: avoid_setters_without_getters + external set collection(JSString value); + // ignore: avoid_setters_without_getters + external set documentIdExpression(JSAny value); +} + +extension type UpsertStageOptionsJsImpl._(JSObject _) implements JSObject { + UpsertStageOptionsJsImpl() : this._(JSObject.new()); + + // ignore: avoid_setters_without_getters + external set collection(JSString value); + // ignore: avoid_setters_without_getters + external set documentIdExpression(JSAny value); + // ignore: avoid_setters_without_getters + external set additionalFields(JSAny value); +} diff --git a/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_builder_web.dart b/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_builder_web.dart index 6c99e6495c24..81f61d43a74a 100644 --- a/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_builder_web.dart +++ b/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_builder_web.dart @@ -19,6 +19,7 @@ interop.PipelineJsImpl buildPipelineFromStages( final source = jsFirestore.pipeline(); final first = stages.first; final stageName = first['stage'] as String?; + final converter = PipelineExpressionParserWeb(interop.pipelines, jsFirestore); // Build source stage interop.PipelineJsImpl pipeline = _applySourceStage( @@ -26,10 +27,9 @@ interop.PipelineJsImpl buildPipelineFromStages( jsFirestore, stageName, first, + converter, ); - final converter = PipelineExpressionParserWeb(interop.pipelines, jsFirestore); - // Apply remaining stages for (var i = 1; i < stages.length; i++) { pipeline = _applyStage(pipeline, stages[i], converter, jsFirestore); @@ -42,6 +42,7 @@ interop.PipelineJsImpl _applySourceStage( interop.FirestoreJsImpl jsFirestore, String? stageName, Map first, + PipelineExpressionParserWeb converter, ) { final args = first['args']; return switch (stageName) { @@ -59,6 +60,12 @@ interop.PipelineJsImpl _applySourceStage( .toList() .toJS, ), + 'literals' => source.literals( + converter.toLiteralsDocuments( + ((args as Map)['documents'] ?? const []) + as List, + ), + ), _ => throw UnsupportedError( 'Pipeline source stage "$stageName" is not supported on web.', ), @@ -141,6 +148,14 @@ interop.PipelineJsImpl _applyStage( pipelineStages, ); return pipeline.union(otherPipeline); + case 'delete': + return pipeline.delete(interop.DeleteStageOptionsJsImpl()); + case 'update': + return pipeline.update(converter.toUpdateOptions(map)); + case 'insert': + return pipeline.insert(converter.toInsertOptions(map)); + case 'upsert': + return pipeline.upsert(converter.toUpsertOptions(map)); default: throw FirebaseException( plugin: 'cloud_firestore', diff --git a/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_expression_parser_web.dart b/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_expression_parser_web.dart index 06b4473c7a0e..1785c00ba7a0 100644 --- a/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_expression_parser_web.dart +++ b/packages/cloud_firestore/cloud_firestore_web/lib/src/pipeline_expression_parser_web.dart @@ -678,6 +678,70 @@ class PipelineExpressionParserWeb { interop.AddFieldsOptionsJsImpl() ..fields = _toSelectableList(expressions).toJS; + /// Converts a literals source document list into a JS array of objects. + JSAny toLiteralsDocuments(List documents) { + final objects = documents.map((document) { + final fields = document as Map; + final object = JSObject(); + for (final entry in fields.entries) { + final tagged = Map.from(entry.value as Map); + final JSAny? jsValue; + if (tagged['kind'] == 'expression') { + jsValue = toExpression( + Map.from(tagged['expression'] as Map), + ); + } else { + jsValue = _literalValueToJs(tagged['value']); + } + object.setProperty(entry.key.toString().toJS, jsValue); + } + return object; + }).toList(); + return objects.toJS; + } + + /// Converts an update stage into JS UpdateStageOptions. + JSAny toUpdateOptions(Map map) { + final options = interop.UpdateStageOptionsJsImpl(); + final expressions = map['expressions'] as List?; + if (expressions != null && expressions.isNotEmpty) { + options.transformedFields = _toSelectableList(expressions).toJS; + } + return options; + } + + /// Converts an insert stage into JS InsertStageOptions. + JSAny toInsertOptions(Map map) { + final options = interop.InsertStageOptionsJsImpl(); + _applyWriteTarget(options, map); + return options; + } + + /// Converts an upsert stage into JS UpsertStageOptions. + JSAny toUpsertOptions(Map map) { + final options = interop.UpsertStageOptionsJsImpl(); + _applyWriteTarget(options, map); + final additionalFields = map['additional_fields'] as List?; + if (additionalFields != null && additionalFields.isNotEmpty) { + options.additionalFields = _toSelectableList(additionalFields).toJS; + } + return options; + } + + void _applyWriteTarget(JSObject options, Map map) { + final collection = map['collection'] as String?; + if (collection != null) { + options.setProperty('collection'.toJS, collection.toJS); + } + final documentId = map['document_id']; + if (documentId is Map) { + options.setProperty( + 'documentIdExpression'.toJS, + toExpression(Map.from(documentId)), + ); + } + } + /// Converts select stage expressions to JS SelectStageOptions. JSAny toSelectOptions(List expressions) => interop.SelectStageOptionsJsImpl() @@ -833,6 +897,24 @@ class PipelineExpressionParserWeb { // ── Private helpers ─────────────────────────────────────────────────────── + /// Converts a literals field value into a JS value the Firestore SDK accepts. + /// + /// Lists become JS arrays. Nested maps stay maps. [List] is an array + /// of numbers here; byte values are [Blob]. + JSAny? _literalValueToJs(Object? value) { + if (value is Map) { + final object = JSObject(); + value.forEach((key, nested) { + object.setProperty(key.toString().toJS, _literalValueToJs(nested)); + }); + return object; + } + if (value is List) { + return value.map(_literalValueToJs).toList().toJS; + } + return _constantValueToJs(value); + } + /// Converts a [Constant] value to the correct JS type for the pipelines API. /// /// Each Dart type accepted by [Constant] is mapped to the corresponding diff --git a/packages/cloud_firestore/cloud_firestore_web/test/pipeline_writes_web_test.dart b/packages/cloud_firestore/cloud_firestore_web/test/pipeline_writes_web_test.dart new file mode 100644 index 000000000000..3b64f2e60e7d --- /dev/null +++ b/packages/cloud_firestore/cloud_firestore_web/test/pipeline_writes_web_test.dart @@ -0,0 +1,223 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@TestOn('chrome') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:cloud_firestore_web/src/interop/firestore_interop.dart' + as interop; +import 'package:cloud_firestore_web/src/pipeline_builder_web.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + late JSObject source; + late JSObject pipeline; + late JSAny? literalsDocuments; + late JSAny? updateOptions; + late JSAny? insertOptions; + late JSAny? upsertOptions; + late JSAny? deleteOptions; + + setUp(() { + literalsDocuments = null; + updateOptions = null; + insertOptions = null; + upsertOptions = null; + deleteOptions = null; + + JSObject expression() { + final expr = JSObject(); + expr['as'] = ((JSAny? alias) => expr).toJS; + return expr; + } + + final pipelinesModule = JSObject(); + pipelinesModule['field'] = ((JSAny? path) => expression()).toJS; + pipelinesModule['constant'] = ((JSAny? value) => expression()).toJS; + + pipeline = JSObject(); + pipeline['update'] = ((JSAny options) { + updateOptions = options; + return pipeline; + }).toJS; + pipeline['insert'] = ((JSAny options) { + insertOptions = options; + return pipeline; + }).toJS; + pipeline['upsert'] = ((JSAny options) { + upsertOptions = options; + return pipeline; + }).toJS; + pipeline['delete'] = ((JSAny options) { + deleteOptions = options; + return pipeline; + }).toJS; + + source = JSObject(); + source['literals'] = ((JSAny documents) { + literalsDocuments = documents; + return pipeline; + }).toJS; + source['collection'] = ((JSAny path) => pipeline).toJS; + + final firestoreSdk = JSObject(); + firestoreSdk['pipelines'] = pipelinesModule; + globalContext['firebase_firestore'] = firestoreSdk; + }); + + interop.FirestoreJsImpl firestore() { + final raw = JSObject(); + raw['pipeline'] = (() => source).toJS; + return raw as interop.FirestoreJsImpl; + } + + test( + 'literals, upsert, insert, update, and delete reach the JS stage methods', + () { + buildPipelineFromStages(firestore(), [ + { + 'stage': 'literals', + 'args': { + 'documents': [ + { + 'name': {'kind': 'value', 'value': 'ada'}, + 'tags': { + 'kind': 'value', + 'value': ['a', 'b'], + }, + 'score': { + 'kind': 'expression', + 'expression': { + 'name': 'constant', + 'args': {'value': 1}, + }, + }, + }, + ], + }, + }, + { + 'stage': 'upsert', + 'args': { + 'collection': 'pipeline-writes', + 'document_id': { + 'name': 'constant', + 'args': {'value': 'ada'}, + }, + 'additional_fields': [ + { + 'name': 'alias', + 'args': { + 'alias': 'extra', + 'expression': { + 'name': 'field', + 'args': {'field': 'name'}, + }, + }, + }, + ], + }, + }, + ]); + + final documents = (literalsDocuments! as JSArray).toDart; + expect(documents, hasLength(1)); + final document = documents.first! as JSObject; + expect(document.getProperty('name'.toJS).dartify(), 'ada'); + expect(document.getProperty('tags'.toJS).dartify(), ['a', 'b']); + expect(document.getProperty('score'.toJS), isNotNull); + + final upsert = upsertOptions! as JSObject; + expect( + upsert.getProperty('collection'.toJS).dartify(), + 'pipeline-writes', + ); + expect(upsert.getProperty('documentIdExpression'.toJS), isNotNull); + expect(upsert.getProperty('documentId'.toJS), isNull); + expect(upsert.getProperty('additionalFields'.toJS), isA()); + expect(upsert.getProperty('additional_fields'.toJS), isNull); + + buildPipelineFromStages(firestore(), [ + { + 'stage': 'collection', + 'args': {'path': 'pipeline-writes'}, + }, + { + 'stage': 'update', + 'args': { + 'expressions': [ + { + 'name': 'alias', + 'args': { + 'alias': 'score', + 'expression': { + 'name': 'field', + 'args': {'field': 'rating'}, + }, + }, + }, + ], + }, + }, + ]); + + final update = updateOptions! as JSObject; + expect(update.getProperty('transformedFields'.toJS), isA()); + expect(update.getProperty('expressions'.toJS), isNull); + + buildPipelineFromStages(firestore(), [ + { + 'stage': 'literals', + 'args': { + 'documents': [ + { + 'name': {'kind': 'value', 'value': 'grace'}, + }, + ], + }, + }, + { + 'stage': 'insert', + 'args': { + 'collection': 'pipeline-writes', + 'document_id': { + 'name': 'constant', + 'args': {'value': 'grace'}, + }, + }, + }, + ]); + + final insert = insertOptions! as JSObject; + expect( + insert.getProperty('collection'.toJS).dartify(), + 'pipeline-writes', + ); + expect(insert.getProperty('documentIdExpression'.toJS), isNotNull); + expect(insert.getProperty('documentId'.toJS), isNull); + + buildPipelineFromStages(firestore(), [ + { + 'stage': 'collection', + 'args': {'path': 'pipeline-writes'}, + }, + {'stage': 'delete', 'args': {}}, + ]); + expect(deleteOptions, isA()); + }, + ); + + test('a literals stage with no documents list still builds', () { + buildPipelineFromStages(firestore(), [ + {'stage': 'literals', 'args': {}}, + {'stage': 'delete', 'args': {}}, + ]); + + expect((literalsDocuments! as JSArray).toDart, isEmpty); + expect(deleteOptions, isA()); + }); +}