@@ -1475,6 +1475,7 @@ export class Query<
14751475 toProto (
14761476 transactionOrReadTime ?: Uint8Array | Timestamp | api . ITransactionOptions ,
14771477 explainOptions ?: firestore . ExplainOptions ,
1478+ forceImplicitOrderBy ?: boolean ,
14781479 ) : api . IRunQueryRequest {
14791480 const projectId = this . firestore . projectId ;
14801481 const databaseId = this . firestore . databaseId ;
@@ -1483,18 +1484,18 @@ export class Query<
14831484 databaseId ,
14841485 ) ;
14851486
1486- const structuredQuery = this . toStructuredQuery ( ) ;
1487+ const structuredQuery = this . toStructuredQuery ( forceImplicitOrderBy ) ;
14871488
14881489 // For limitToLast queries, the structured query has to be translated to a version with
14891490 // reversed ordered, and flipped startAt/endAt to work properly.
14901491 if ( this . _queryOptions . limitType === LimitType . Last ) {
1491- if ( ! this . _queryOptions . hasFieldOrders ( ) ) {
1492- throw new Error (
1493- 'limitToLast() queries require specifying at least one orderBy() clause.' ,
1494- ) ;
1495- }
1492+ const forceImplicit =
1493+ forceImplicitOrderBy || this . _firestore . alwaysUseImplicitOrderBy ;
1494+ const fieldOrders = forceImplicit
1495+ ? this . createImplicitOrderBy ( )
1496+ : this . _queryOptions . fieldOrders ;
14961497
1497- structuredQuery . orderBy = this . _queryOptions . fieldOrders ! . map ( order => {
1498+ structuredQuery . orderBy = fieldOrders . map ( order => {
14981499 // Flip the orderBy directions since we want the last results
14991500 const dir =
15001501 order . direction === 'DESCENDING' ? 'ASCENDING' : 'DESCENDING' ;
@@ -1564,7 +1565,9 @@ export class Query<
15641565 return bundledQuery ;
15651566 }
15661567
1567- private toStructuredQuery ( ) : api . IStructuredQuery {
1568+ private toStructuredQuery (
1569+ forceImplicitOrderBy ?: boolean ,
1570+ ) : api . IStructuredQuery {
15681571 const structuredQuery : api . IStructuredQuery = {
15691572 from : [ { } ] ,
15701573 } ;
@@ -1586,9 +1589,19 @@ export class Query<
15861589 ) . toProto ( ) ;
15871590 }
15881591
1589- if ( this . _queryOptions . hasFieldOrders ( ) ) {
1590- structuredQuery . orderBy = this . _queryOptions . fieldOrders . map ( o =>
1591- o . toProto ( ) ,
1592+ // orders
1593+ const forceImplicit =
1594+ forceImplicitOrderBy || this . _firestore . alwaysUseImplicitOrderBy ;
1595+ let fieldOrders = this . _queryOptions . fieldOrders ;
1596+ if ( forceImplicit ) {
1597+ fieldOrders = this . createImplicitOrderBy ( ) ;
1598+ }
1599+
1600+ if ( fieldOrders . length > 0 ) {
1601+ structuredQuery . orderBy = fieldOrders . map ( o => o . toProto ( ) ) ;
1602+ } else if ( this . _queryOptions . limitType === LimitType . Last ) {
1603+ throw new Error (
1604+ 'limitToLast() queries require specifying at least one orderBy() clause.' ,
15921605 ) ;
15931606 }
15941607
0 commit comments