@mastra/cloudflare-d1 1.5.1 → 1.5.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,6 +9,20 @@ import { saveScorePayloadSchema } from "@mastra/core/evals";
9
9
  function isArrayOfRecords(value) {
10
10
  return value && Array.isArray(value) && value.length > 0;
11
11
  }
12
+ /**
13
+ * Builds an `IN` condition that takes the whole id list as a single bound parameter.
14
+ *
15
+ * D1 caps a statement at 100 bound parameters, so interpolating one `?` per id made
16
+ * `listMessagesById`/`updateMessages`/`deleteMessages` fail with "too many SQL variables" for
17
+ * threads holding more than ~100 messages. Binding the list once as a JSON array keeps the
18
+ * parameter count constant no matter how many ids the caller passes, and `json_each` is part of
19
+ * SQLite's JSON1 extension, which D1 enables.
20
+ *
21
+ * Callers must bind `JSON.stringify(values)` for the returned placeholder.
22
+ */
23
+ function inJsonArray(column) {
24
+ return `${column} IN (SELECT value FROM json_each(?))`;
25
+ }
12
26
  function deserializeValue(value, type) {
13
27
  if (value === null || value === void 0) return null;
14
28
  if (type === "date" && typeof value === "string") return new Date(value);
@@ -1627,10 +1641,9 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1627
1641
  const resourceCondition = resourceId ? ` AND resourceId = ?` : "";
1628
1642
  const targetIds = include.map((inc) => inc.id).filter(Boolean);
1629
1643
  if (targetIds.length === 0) return null;
1630
- const idPlaceholders = targetIds.map(() => "?").join(", ");
1631
1644
  const targetResult = await this.#db.executeQuery({
1632
- sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE id IN (${idPlaceholders})${resourceCondition}`,
1633
- params: resourceId ? [...targetIds, resourceId] : targetIds
1645
+ sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE ${inJsonArray("id")}${resourceCondition}`,
1646
+ params: resourceId ? [JSON.stringify(targetIds), resourceId] : [JSON.stringify(targetIds)]
1634
1647
  });
1635
1648
  if (!Array.isArray(targetResult) || targetResult.length === 0) return null;
1636
1649
  const targetMap = new Map(targetResult.map((r) => [r.id, {
@@ -1712,7 +1725,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1712
1725
  "createdAt",
1713
1726
  "thread_id AS threadId",
1714
1727
  "resourceId"
1715
- ]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
1728
+ ]).from(fullTableName).where(inJsonArray("id"), JSON.stringify(messageIds));
1716
1729
  query.orderBy("createdAt", "DESC");
1717
1730
  const { sql, params } = query.build();
1718
1731
  const result = await this.#db.executeQuery({
@@ -1763,13 +1776,12 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1763
1776
  const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
1764
1777
  try {
1765
1778
  const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1766
- const threadPlaceholders = threadIds.map(() => "?").join(", ");
1767
1779
  let query = `
1768
1780
  SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1769
1781
  FROM ${fullTableName}
1770
- WHERE thread_id IN (${threadPlaceholders})
1782
+ WHERE ${inJsonArray("thread_id")}
1771
1783
  `;
1772
- const queryParams = [...threadIds];
1784
+ const queryParams = [JSON.stringify(threadIds)];
1773
1785
  if (resourceId) {
1774
1786
  query += ` AND resourceId = ?`;
1775
1787
  queryParams.push(resourceId);
@@ -1834,8 +1846,8 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1834
1846
  return processedMsg;
1835
1847
  });
1836
1848
  const paginatedCount = paginatedMessages.length;
1837
- let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id IN (${threadPlaceholders})`;
1838
- const countParams = [...threadIds];
1849
+ let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE ${inJsonArray("thread_id")}`;
1850
+ const countParams = [JSON.stringify(threadIds)];
1839
1851
  if (resourceId) {
1840
1852
  countQuery += ` AND resourceId = ?`;
1841
1853
  countParams.push(resourceId);
@@ -1888,7 +1900,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1888
1900
  total,
1889
1901
  page,
1890
1902
  perPage: perPageForResponse,
1891
- hasMore: metadataFilter ? perPageInput !== false && offset + paginatedCount < total : perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total
1903
+ hasMore: metadataFilter || dateRange?.start || dateRange?.end ? perPageInput !== false && offset + paginatedCount < total : perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total
1892
1904
  };
1893
1905
  } catch (error) {
1894
1906
  if (error instanceof MastraError && error.category === ErrorCategory.USER) throw error;
@@ -1919,10 +1931,10 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1919
1931
  const fullTableName = this.#db.getTableName(TABLE_MESSAGES);
1920
1932
  const threadsTableName = this.#db.getTableName(TABLE_THREADS);
1921
1933
  try {
1922
- const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${messageIds.map(() => "?").join(",")})`;
1934
+ const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE ${inJsonArray("id")}`;
1923
1935
  const existingMessages = await this.#db.executeQuery({
1924
1936
  sql: selectQuery,
1925
- params: messageIds
1937
+ params: [JSON.stringify(messageIds)]
1926
1938
  });
1927
1939
  if (existingMessages.length === 0) return [];
1928
1940
  const parsedExistingMessages = existingMessages.map((msg) => {
@@ -1973,10 +1985,10 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1973
1985
  }
1974
1986
  for (const query of updateQueries) await executeFenced(this.#db, check, query);
1975
1987
  if (threadIdsToUpdate.size > 0) {
1976
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})${guardSql}`;
1988
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE ${inJsonArray("id")}${guardSql}`;
1977
1989
  const threadUpdateParams = [
1978
1990
  (/* @__PURE__ */ new Date()).toISOString(),
1979
- ...Array.from(threadIdsToUpdate),
1991
+ JSON.stringify(Array.from(threadIdsToUpdate)),
1980
1992
  ...guardParams
1981
1993
  ];
1982
1994
  await executeFenced(this.#db, check, {
@@ -1986,7 +1998,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
1986
1998
  }
1987
1999
  return (await this.#db.executeQuery({
1988
2000
  sql: selectQuery,
1989
- params: messageIds
2001
+ params: [JSON.stringify(messageIds)]
1990
2002
  })).map((message) => {
1991
2003
  if (typeof message.content === "string") try {
1992
2004
  message.content = JSON.parse(message.content);
@@ -2010,20 +2022,19 @@ var MemoryStorageD1 = class MemoryStorageD1 extends MemoryStorage {
2010
2022
  const check = this.#runFenceCheck(options?.fence, "deleteMessages");
2011
2023
  const guard = runFenceGuard(check);
2012
2024
  try {
2013
- const placeholders = messageIds.map(() => "?").join(",");
2014
- const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE id IN (${placeholders})`;
2025
+ const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE ${inJsonArray("id")}`;
2015
2026
  const threadIds = (await this.#db.executeQuery({
2016
2027
  sql: selectQuery,
2017
- params: messageIds
2028
+ params: [JSON.stringify(messageIds)]
2018
2029
  })).map((r) => r.thread_id).filter(Boolean);
2019
- const deleteQuery = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds);
2030
+ const deleteQuery = createSqlBuilder().delete(fullTableName).where(inJsonArray("id"), JSON.stringify(messageIds));
2020
2031
  if (guard) deleteQuery.andWhere(guard.sql, ...guard.params);
2021
2032
  await executeFenced(this.#db, check, deleteQuery.build());
2022
2033
  if (threadIds.length > 0) {
2023
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})${guard ? ` AND ${guard.sql}` : ""}`;
2034
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE ${inJsonArray("id")}${guard ? ` AND ${guard.sql}` : ""}`;
2024
2035
  const threadUpdateParams = [
2025
2036
  (/* @__PURE__ */ new Date()).toISOString(),
2026
- ...threadIds,
2037
+ JSON.stringify(threadIds),
2027
2038
  ...guard?.params ?? []
2028
2039
  ];
2029
2040
  await executeFenced(this.#db, check, {