Skip to content

Allow joins with an and() condition #593

Description

@duailibe

Trying to join collections using a condition with an and() is not supported right now.

Reproduction

Adding packages/db/tests/query/join.test.ts:

type Product = {
  productId: number;
  region: 'A' | 'B' | 'C';
  sku: string;
  title: string;
}

type ProductInventory = {
  inventoryId: number;
  region: 'A' | 'B' | 'C';
  sku: string;
  quantity: number;
};

test('join with and', () => {
  const productsCollection = createCollection(
    mockSyncCollectionOptions<Product>({
      id: `test-products-join`,
      getKey: (product) => product.productId,
      initialData: [
        { productId: 1, region: 'A', sku: 'sku1', title: 'A1' },
        { productId: 2, region: 'B', sku: 'sku1', title: 'B1' },
        { productId: 3, region: 'C', sku: 'sku2', title: 'C2' },
        { productId: 4, region: 'A', sku: 'sku2', title: 'A2' },
      ],
    })
  );
  const inventoriesCollection = createCollection(
    mockSyncCollectionOptions<ProductInventory>({
      id: `test-inventories-join`,
      getKey: (inventory) => inventory.inventoryId,
      initialData: [
        { inventoryId: 1, region: 'A', sku: 'sku1', quantity: 10 },
        { inventoryId: 3, region: 'C', sku: 'sku2', quantity: 30 },
      ],
    })
  );

  const joinQuery = createLiveQueryCollection({
    startSync: true,
    query: (q) =>
      q
        .from({ product: productsCollection })
        .join(
          { inventory: inventoriesCollection },
          ({ product, inventory }) =>
            and(
              eq(product.region, product.sku),
              eq(inventory.region, inventory.sku)
            ),
        )
  });

  expect(joinQuery.toArray).toHaveLength(2);
});

And it fails with:

QueryBuilderError: Join condition must be an equality expression
 ❯ BaseQueryBuilder.join src/query/builder/index.ts:277:3
    275|   > {
    276|     return this.join(source, onCallback, `inner`)
    277|   }
       |   ^
    278|
    279|   /**
 ❯ query tests/query/join.test.ts:1459:10
 ❯ buildQuery src/query/builder/index.ts:3822:45
 ❯ buildQueryFromConfig src/query/live/collection-config-builder.ts:3737:48
 ❯ new CollectionConfigBuilder src/query/live/collection-config-builder.ts:139:9
 ❯ liveQueryCollectionOptions src/query/live-query-collection.ts:269:60
 ❯ createLiveQueryCollection src/query/live-query-collection.ts:287:46

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions