Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: handle fetching data from tables with more 1000 results
Brad Barbince74c76fd927
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 40d9e5b6cb..f64d860d65 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -1,6 +1,7 @@"use client";import { useCarbon } from "@carbon/auth";+import { fetchAllFromTable } from "@carbon/database";import type { RealtimeChannel } from "@supabase/supabase-js";import { useEffect, useRef } from "react";import { useUser } from "~/hooks";@@ -49,29 +50,45 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {if (!carbon || !accessToken || hydratedFromServer) return;const [items, suppliers, customers, people] = await Promise.all([- carbon- .from("item")- .select(- "id, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType"- )- .eq("companyId", companyId)- .order("readableId", { ascending: true })- .order("revision", { ascending: false }),- carbon- .from("supplier")- .select("id, name")- .eq("companyId", companyId)- .order("name"),- carbon- .from("customer")- .select("id, name")- .eq("companyId", companyId)- .order("name"),- carbon- .from("employees")- .select("id, name, email, avatarUrl")- .eq("companyId", companyId)- .order("name"),+ fetchAllFromTable<{+ id: string;+ readableIdWithRevision: string;+ unitOfMeasureCode: string;+ name: string;+ type: string;+ replenishmentSystem: string;+ active: boolean;+ itemTrackingType: string;+ }>(+ carbon,+ "item",+ "id, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType",+ (query) =>+ query+ .eq("companyId", companyId)+ .order("readableId", { ascending: true })+ .order("revision", { ascending: false })+ ),+ fetchAllFromTable<{+ id: string;+ name: string;+ }>(carbon, "supplier", "id, name", (query) =>+ query.eq("companyId", companyId).order("name")+ ),+ fetchAllFromTable<{+ id: string;+ name: string;+ }>(carbon, "customer", "id, name", (query) =>+ query.eq("companyId", companyId).order("name")+ ),+ fetchAllFromTable<{+ id: string;+ name: string;+ email: string;+ avatarUrl: string;+ }>(carbon, "employees", "id, name, email, avatarUrl", (query) =>+ query.eq("companyId", companyId).order("name")+ ),]);if (items.error) {diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 5bde07a8cd..e571e88df4 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -1,4 +1,4 @@-import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable, type Database, type Json } from "@carbon/database";import { getLocalTimeZone, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";@@ -319,12 +319,12 @@ export async function getShelvesList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("shelf")- .select("id, name")- .eq("active", true)- .eq("companyId", companyId)- .order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ }>(client, "shelf", "id, name", (query) =>+ query.eq("active", true).eq("companyId", companyId).order("name")+ );}export async function getShelvesListForLocation(@@ -332,13 +332,16 @@ export async function getShelvesListForLocation(companyId: string,locationId: string) {- return client- .from("shelf")- .select("id, name")- .eq("active", true)- .eq("companyId", companyId)- .eq("locationId", locationId)- .order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ }>(client, "shelf", "id, name", (query) =>+ query+ .eq("active", true)+ .eq("companyId", companyId)+ .eq("locationId", locationId)+ .order("name")+ );}export async function getShelves(diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 5624d777f4..8e47810212 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1,4 +1,5 @@import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable } from "@carbon/database";import { getLocalTimeZone, today } from "@internationalized/date";import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";@@ -393,14 +394,17 @@ export async function getConsumablesList(client: SupabaseClient<Database>,companyId: string) {- let query = client- .from("item")- .select("id, name, readableIdWithRevision")- .eq("type", "Consumable")- .eq("companyId", companyId)- .eq("active", true);-- return query.order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ readableIdWithRevision: string;+ }>(client, "item", "id, name, readableIdWithRevision", (query) =>+ query+ .eq("type", "Consumable")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name")+ );}export async function getItem(client: SupabaseClient<Database>, id: string) {return client.from("item").select("*").eq("id", id).single();@@ -811,14 +815,17 @@ export async function getMaterialsList(client: SupabaseClient<Database>,companyId: string) {- let query = client- .from("item")- .select("id, name, readableIdWithRevision")- .eq("type", "Material")- .or(`companyId.eq.${companyId},companyId.is.null`)- .eq("active", true);-- return query.order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ readableIdWithRevision: string;+ }>(client, "item", "id, name, readableIdWithRevision", (query) =>+ query+ .eq("type", "Material")+ .or(`companyId.eq.${companyId},companyId.is.null`)+ .eq("active", true)+ .order("name")+ );}export async function getMaterialDimension(@@ -1325,14 +1332,17 @@ export async function getPartsList(client: SupabaseClient<Database>,companyId: string) {- let query = client- .from("item")- .select("id, name, readableIdWithRevision")- .eq("type", "Part")- .eq("companyId", companyId)- .eq("active", true);-- return query.order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ readableIdWithRevision: string;+ }>(client, "item", "id, name, readableIdWithRevision", (query) =>+ query+ .eq("type", "Part")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name")+ );}export async function getPartUsedIn(@@ -1518,15 +1528,16 @@ export async function getServicesList(client: SupabaseClient<Database>,companyId: string) {- let query = client- .from("item")- .select("id, name")- .eq("type", "Service")- .eq("companyId", companyId)- .eq("active", true)- .order("name");-- return query;+ return fetchAllFromTable<{+ id: string;+ name: string;+ }>(client, "item", "id, name", (query) =>+ query+ .eq("type", "Service")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name")+ );}export async function getSupplierParts(@@ -1589,14 +1600,17 @@ export async function getToolsList(client: SupabaseClient<Database>,companyId: string) {- let query = client- .from("item")- .select("id, name, readableIdWithRevision")- .eq("type", "Tool")- .eq("companyId", companyId)- .eq("active", true);-- return query.order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ readableIdWithRevision: string;+ }>(client, "item", "id, name, readableIdWithRevision", (query) =>+ query+ .eq("type", "Tool")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name")+ );}export async function getUnitOfMeasure(diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex e52479a513..409ad0718d 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -1,4 +1,4 @@-import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable, type Database, type Json } from "@carbon/database";import type { JSONContent } from "@carbon/react";import type { FileObject, StorageError } from "@supabase/storage-js";import {@@ -266,11 +266,12 @@ export async function getJobsList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("job")- .select("id, jobId")- .eq("companyId", companyId)- .order("jobId");+ return fetchAllFromTable<{+ id: string;+ jobId: string;+ }>(client, "job", "id, jobId", (query) =>+ query.eq("companyId", companyId).order("jobId")+ );}export async function getJobMakeMethodById(@@ -623,12 +624,16 @@ export async function getProceduresList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("procedure")- .select("*")- .eq("companyId", companyId)- .order("name", { ascending: true })- .order("version", { ascending: false });+ return fetchAllFromTable<{+ id: string;+ name: string;+ version: number;+ }>(client, "procedure", "id, name, version", (query) =>+ query+ .eq("companyId", companyId)+ .order("name", { ascending: true })+ .order("version", { ascending: false })+ );}export async function getProductionEvent(diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex fad6a6ba06..a3004a9ca2 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1,4 +1,4 @@-import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable, type Database, type Json } from "@carbon/database";import { getLocalTimeZone, today } from "@internationalized/date";import {FunctionRegion,@@ -625,11 +625,12 @@ export async function getSupplierQuotesList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("supplierQuote")- .select("id, supplierQuoteId")- .eq("companyId", companyId)- .order("createdAt", { ascending: false });+ return fetchAllFromTable<{+ id: string;+ supplierQuoteId: string;+ }>(client, "supplierQuote", "id, supplierQuoteId", (query) =>+ query.eq("companyId", companyId).order("createdAt", { ascending: false })+ );}export async function getSupplierShipping(@@ -681,11 +682,12 @@ export async function getSuppliersList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("supplier")- .select("id, name")- .eq("companyId", companyId)- .order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ }>(client, "supplier", "id, name", (query) =>+ query.eq("companyId", companyId).order("name")+ );}export async function getSupplierStatus(diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 75cfcc5978..43c3eab155 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -1,4 +1,4 @@-import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable, type Database, type Json } from "@carbon/database";import { parseDate } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";@@ -187,10 +187,14 @@ export async function getGaugesList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("gauge")- .select("id, name:gaugeId, description")- .eq("companyId", companyId);+ return fetchAllFromTable<{+ id: string;+ name: string;+ gaugeId: string;+ description: string;+ }>(client, "gauge", "id, name:gaugeId, description", (query) =>+ query.eq("companyId", companyId)+ );}export async function getGaugeCalibrationRecord(diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 8b6a530349..5767f1b03a 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -1,4 +1,4 @@-import type { Database, Json } from "@carbon/database";+import { fetchAllFromTable, type Database, type Json } from "@carbon/database";import { getLocalTimeZone, now, today } from "@internationalized/date";import {FunctionRegion,@@ -443,11 +443,12 @@ export async function getCustomersList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("customer")- .select("id, name")- .eq("companyId", companyId)- .order("name");+ return fetchAllFromTable<{+ id: string;+ name: string;+ }>(client, "customer", "id, name", (query) =>+ query.eq("companyId", companyId).order("name")+ );}export async function getCustomerStatus(@@ -785,11 +786,13 @@ export async function getQuotesList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("quote")- .select("id, quoteId, revisionId")- .eq("companyId", companyId)- .order("createdAt", { ascending: false });+ return fetchAllFromTable<{+ id: string;+ quoteId: string;+ revisionId: string;+ }>(client, "quote", "id, quoteId, revisionId", (query) =>+ query.eq("companyId", companyId).order("createdAt", { ascending: false })+ );}export async function getQuoteAssembliesByLine(@@ -1246,10 +1249,12 @@ export async function getSalesOrdersList(client: SupabaseClient<Database>,companyId: string) {- return client- .from("salesOrder")- .select("id, salesOrderId")- .eq("companyId", companyId);+ return fetchAllFromTable<{+ id: string;+ salesOrderId: string;+ }>(client, "salesOrder", "id, salesOrderId", (query) =>+ query.eq("companyId", companyId)+ );}export async function getSalesOrderPayment(diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex 1c56984456..dcb97bdda7 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -1,4 +1,5 @@import type { Database } from "@carbon/database";+import { fetchAllFromTable } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";@@ -224,11 +225,12 @@ export async function getSuppliers(}export async function getUsers(client: SupabaseClient<Database>) {- return client- .from("user")- .select("id, firstName, lastName, fullName, email, avatarUrl")- .eq("active", true)- .order("lastName");+ return fetchAllFromTable(+ client,+ "user",+ "id, firstName, lastName, fullName, email, avatarUrl",+ (query) => query.eq("active", true).order("lastName")+ );}export async function insertEmployeeType(diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsxindex e2a11f5601..f230cb836e 100644--- a/apps/erp/app/routes/x+/part+/$itemId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx@@ -1,4 +1,4 @@-import { error, getCarbonServiceRole } from "@carbon/auth";+import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { Outlet } from "@remix-run/react";@@ -23,21 +23,25 @@ export const handle: Handle = {};export async function loader({ request, params }: LoaderFunctionArgs) {- const { companyId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "parts",+ bypassRls: true,});const { itemId } = params;if (!itemId) throw new Error("Could not find itemId");- const serviceRole = await getCarbonServiceRole();const [partSummary, supplierParts, pickMethods, tags] = await Promise.all([- getPart(serviceRole, itemId, companyId),- getSupplierParts(serviceRole, itemId, companyId),- getPickMethods(serviceRole, itemId, companyId),- getTagsList(serviceRole, companyId, "part"),+ getPart(client, itemId, companyId),+ getSupplierParts(client, itemId, companyId),+ getPickMethods(client, itemId, companyId),+ getTagsList(client, companyId, "part"),]);+ if (partSummary.data?.companyId !== companyId) {+ throw redirect(path.to.items);+ }+if (partSummary.error) {throw redirect(path.to.items,@@ -50,10 +54,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return defer({partSummary: partSummary.data,- files: getItemFiles(serviceRole, itemId, companyId),+ files: getItemFiles(client, itemId, companyId),supplierParts: supplierParts.data ?? [],pickMethods: pickMethods.data ?? [],- makeMethods: getMakeMethods(serviceRole, itemId, companyId),+ makeMethods: getMakeMethods(client, itemId, companyId),tags: tags.data ?? [],});}diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsxindex 52840ea890..84cbded47a 100644--- a/apps/mes/app/components/RealtimeDataProvider.tsx+++ b/apps/mes/app/components/RealtimeDataProvider.tsx@@ -1,6 +1,7 @@"use client";import { useCarbon } from "@carbon/auth";+import { fetchAllFromTable } from "@carbon/database";import idb from "localforage";import { useEffect } from "react";import { useUser } from "~/hooks";@@ -39,20 +40,22 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {if (!carbon || !accessToken || hydratedFromServer) return;const [items, people] = await Promise.all([- carbon- .from("item")- .select(- "id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active"- )- .eq("companyId", companyId)- .order("readableId", { ascending: true })- .order("revision", { ascending: false }),-- carbon- .from("employees")- .select("id, name, email, avatarUrl")- .eq("companyId", companyId)- .order("name"),+ fetchAllFromTable(+ carbon,+ "item",+ "id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active",+ (query) =>+ query+ .eq("companyId", companyId)+ .order("readableId", { ascending: true })+ .order("revision", { ascending: false })+ ),+ fetchAllFromTable(+ carbon,+ "employees",+ "id, name, email, avatarUrl",+ (query) => query.eq("companyId", companyId).order("name")+ ),]);if (items.error) {diff --git a/docs/supabase-pagination.md b/docs/supabase-pagination.mdnew file mode 100644index 0000000000..e3c7df3e5a--- /dev/null+++ b/docs/supabase-pagination.md@@ -0,0 +1,179 @@+# Supabase Pagination Utilities++## Overview++Supabase has a default limit of 1000 rows per request. To handle queries that might return more than 1000 rows, we've implemented pagination utilities that automatically handle batching and fetching all records.++## Utilities++### `fetchAllRecords<T>(baseQuery)`++Fetches all records from a Supabase query by automatically handling pagination.++```typescript+import { fetchAllRecords } from "~/utils/supabase-pagination";++const query = client.from("items").select("*").eq("companyId", companyId);++const result = await fetchAllRecords(query);+// result.data contains ALL items, not just first 1000+```++### `fetchAllFromTable<T>(client, tableName, selectColumns, filterFn)`++Helper function for simple table queries that need all records.++```typescript+import { fetchAllFromTable } from "@carbon/database";++const result = await fetchAllFromTable(+ client,+ "items",+ "id, name, type",+ (query) => query.eq("companyId", companyId).eq("active", true).order("name")+);+```++### `fetchRecordsInBatches<T>(baseQuery, batchSize)`++Async generator for processing large datasets in batches.++```typescript+import { fetchRecordsInBatches } from "~/utils/supabase-pagination";++const query = client.from("items").select("*").eq("companyId", companyId);++for await (const { data, batch, hasMore } of fetchRecordsInBatches(+ query,+ 500+)) {+ console.log(`Processing batch ${batch} with ${data.length} items`);+ // Process each batch of 500 items+ await processItems(data);+}+```++## When to Use++### ✅ Use pagination utilities for:++- **RealtimeDataProvider queries** - Fetching all items, customers, suppliers, etc. for local storage+- **List functions** - `getPartsList()`, `getMaterialsList()`, etc. used in dropdowns+- **Export functions** - When exporting all records to CSV/Excel+- **Bulk operations** - Processing all records of a certain type+- **Any query that could potentially return >1000 rows**++### ❌ Don't use for:++- **UI pagination** - Use existing `setGenericQueryFilters()` with limit/offset+- **Single record lookups** - `.single()` queries+- **Small datasets** - Tables that will never exceed 1000 rows+- **Performance critical paths** - When you specifically need only the first N records++## Migration Examples++### Before (❌ Could hit 1000 row limit)++```typescript+export async function getItemsList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("item")+ .select("id, name, type")+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name");+}+```++### After (✅ Handles unlimited rows)++```typescript+import { fetchAllFromTable } from "@carbon/database";++export async function getItemsList(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return fetchAllFromTable(client, "item", "id, name, type", (query) =>+ query.eq("companyId", companyId).eq("active", true).order("name")+ );+}+```++## Return Type++All pagination utilities return a `PaginatedResult<T>`:++```typescript+interface PaginatedResult<T> {+ data: T[]; // All fetched records+ count: number | null; // Total count (from first request)+ error: any; // Error if query failed+}+```++## Performance Considerations++- **Batch size**: Default is 1000 (Supabase's limit). Can be customized for memory optimization+- **Memory usage**: All records are loaded into memory. Use `fetchRecordsInBatches` for very large datasets+- **Network requests**: Makes multiple requests automatically. Progress can be tracked with the generator approach+- **Caching**: Results are not cached. Consider implementing caching at the application level for frequently accessed data++## Example: Complex Query with Pagination++```typescript+import { fetchAllRecords } from "~/utils/supabase-pagination";++export async function getAllActiveItemsWithSuppliers(+ client: SupabaseClient<Database>,+ companyId: string+) {+ const query = client+ .from("items")+ .select(+ `+ id,+ name,+ type,+ supplier:supplierId (+ id,+ name+ )+ `+ )+ .eq("companyId", companyId)+ .eq("active", true)+ .order("name");++ const result = await fetchAllRecords(query);++ if (result.error) {+ throw new Error(`Failed to fetch items: ${result.error.message}`);+ }++ return result.data;+}+```++## Testing++When testing functions that use pagination utilities, the utilities will work normally but you can mock them if needed:++```typescript+import { fetchAllFromTable } from "@carbon/database";++// Mock for testing+jest.mock("~/utils/supabase-pagination", () => ({+ fetchAllFromTable: jest.fn(),+}));++// In test+(fetchAllFromTable as jest.Mock).mockResolvedValue({+ data: mockItems,+ count: mockItems.length,+ error: null,+});+```diff --git a/packages/database/src/index.ts b/packages/database/src/index.tsindex eea524d655..9e034905e0 100644--- a/packages/database/src/index.ts+++ b/packages/database/src/index.ts@@ -1 +1,2 @@export * from "./types";+export * from "./utils";diff --git a/packages/database/src/utils.ts b/packages/database/src/utils.tsnew file mode 100644index 0000000000..e78714e394--- /dev/null+++ b/packages/database/src/utils.ts@@ -0,0 +1,132 @@+import type { Database } from "@carbon/database";+import type {+ PostgrestError,+ PostgrestFilterBuilder,+} from "@supabase/postgrest-js";+import type { SupabaseClient } from "@supabase/supabase-js";++const BATCH_SIZE = 1000;++export type PaginatedResult<T> =+ | {+ data: T[];+ count: number;+ error: null;+ }+ | {+ data: null;+ count: null;+ error: PostgrestError;+ };++/**+ * Fetches all records from a table by automatically handling pagination+ * to work around Supabase's 1000 row limit per request+ */+export async function fetchAllRecords<T extends object>(+ baseQuery: PostgrestFilterBuilder<+ Database["public"],+ Record<string, unknown>,+ T[]+ >+): Promise<PaginatedResult<T>> {+ const allData: T[] = [];+ let offset = 0;+ let totalCount: number = 0;+ let hasMore = true;++ while (hasMore) {+ // Clone the query and add range for this batch+ const query = baseQuery.range(offset, offset + BATCH_SIZE - 1);++ const result = await query;++ if (result.error) {+ return {+ data: null,+ count: null,+ error: result.error,+ };+ }++ if (result.data) {+ allData.push(...result.data);+ }++ // Set total count from first request+ if (offset === 0) {+ totalCount = result.count ?? 0;+ }++ // Check if we have more data to fetch+ hasMore = result.data && result.data.length === BATCH_SIZE;+ offset += BATCH_SIZE;+ }++ return {+ data: allData,+ count: totalCount,+ error: null,+ };+}++/**+ * Helper function for simple table queries that need all records+ */+export async function fetchAllFromTable<T extends object>(+ client: SupabaseClient<Database>,+ tableName:+ | keyof Database["public"]["Tables"]+ | keyof Database["public"]["Views"],+ selectColumns: string = "*",+ filterFn?: (query: any) => any+): Promise<PaginatedResult<T>> {+ let baseQuery = client+ // @ts-ignore+ .from(tableName)+ .select(selectColumns, { count: "exact" });++ if (filterFn) {+ baseQuery = filterFn(baseQuery);+ }++ // @ts-ignore+ return fetchAllRecords(baseQuery);+}++/**+ * Fetches records with automatic batching for queries that might exceed 1000 rows+ * Used when you need all records but want to process them in batches+ */+export async function* fetchRecordsInBatches<T extends object>(+ baseQuery: PostgrestFilterBuilder<+ Database["public"],+ Record<string, unknown>,+ T[]+ >,+ batchSize: number = BATCH_SIZE+): AsyncGenerator<{ data: T[]; batch: number; hasMore: boolean }> {+ let offset = 0;+ let batch = 0;+ let hasMore = true;++ while (hasMore) {+ const query = baseQuery.range(offset, offset + batchSize - 1);+ const result = await query;++ if (result.error) {+ throw new Error(`Batch query failed: ${result.error.message}`);+ }++ hasMore = result.data && result.data.length === batchSize;+ batch++;++ yield {+ data: result.data || [],+ batch,+ hasMore,+ };++ offset += batchSize;+ }+}