@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.
@@ -3,7 +3,7 @@ name: mastra-cloudflare-d1
3
3
  description: Documentation for @mastra/cloudflare-d1. Use when working with @mastra/cloudflare-d1 APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/cloudflare-d1"
6
- version: "1.5.1"
6
+ version: "1.5.2-alpha.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,31 +1,31 @@
1
1
  {
2
- "version": "1.5.1",
2
+ "version": "1.5.2-alpha.0",
3
3
  "package": "@mastra/cloudflare-d1",
4
4
  "exports": {
5
5
  "BackgroundTasksStorageD1": {
6
6
  "types": "dist/storage/domains/background-tasks/index.d.ts",
7
7
  "implementation": "dist/index.js",
8
- "line": 749
8
+ "line": 763
9
9
  },
10
10
  "D1Store": {
11
11
  "types": "dist/storage/index.d.ts",
12
12
  "implementation": "dist/index.js",
13
- "line": 2885
13
+ "line": 2896
14
14
  },
15
15
  "MemoryStorageD1": {
16
16
  "types": "dist/storage/domains/memory/index.d.ts",
17
17
  "implementation": "dist/index.js",
18
- "line": 1087
18
+ "line": 1101
19
19
  },
20
20
  "ScoresStorageD1": {
21
21
  "types": "dist/storage/domains/scores/index.d.ts",
22
22
  "implementation": "dist/index.js",
23
- "line": 2061
23
+ "line": 2072
24
24
  },
25
25
  "WorkflowsStorageD1": {
26
26
  "types": "dist/storage/domains/workflows/index.d.ts",
27
27
  "implementation": "dist/index.js",
28
- "line": 2392
28
+ "line": 2403
29
29
  }
30
30
  },
31
31
  "modules": {}
@@ -106,7 +106,7 @@ const storage = new D1Store({
106
106
  })
107
107
  ```
108
108
 
109
- ### Wrangler Configuration
109
+ ### Wrangler configuration
110
110
 
111
111
  Add the D1 database binding to your `wrangler.toml`:
112
112
 
@@ -145,7 +145,7 @@ Or in `wrangler.jsonc`:
145
145
 
146
146
  ## Additional notes
147
147
 
148
- ### Schema Management
148
+ ### Schema management
149
149
 
150
150
  The storage implementation handles schema creation and updates automatically. It creates the following tables:
151
151
 
@@ -213,10 +213,10 @@ export default {
213
213
 
214
214
  > **Warning:** If `init()` isn't called, tables won't be created and storage operations will fail silently or throw errors.
215
215
 
216
- ### Transactions & Consistency
216
+ ### Transactions & consistency
217
217
 
218
218
  Cloudflare D1 provides transactional guarantees for single-row operations. Multiple operations can be executed as a single, all-or-nothing unit of work.
219
219
 
220
- ### Table Creation & Migrations
220
+ ### Table creation & migrations
221
221
 
222
222
  Tables are created automatically when storage is initialized (and can be isolated per environment using the `tablePrefix` option), but advanced schema changes require manual migration and careful planning. Examples include adding columns or changing data types and indexes to avoid data loss.
package/dist/index.cjs CHANGED
@@ -32,6 +32,20 @@ let _mastra_core_evals = require("@mastra/core/evals");
32
32
  function isArrayOfRecords(value) {
33
33
  return value && Array.isArray(value) && value.length > 0;
34
34
  }
35
+ /**
36
+ * Builds an `IN` condition that takes the whole id list as a single bound parameter.
37
+ *
38
+ * D1 caps a statement at 100 bound parameters, so interpolating one `?` per id made
39
+ * `listMessagesById`/`updateMessages`/`deleteMessages` fail with "too many SQL variables" for
40
+ * threads holding more than ~100 messages. Binding the list once as a JSON array keeps the
41
+ * parameter count constant no matter how many ids the caller passes, and `json_each` is part of
42
+ * SQLite's JSON1 extension, which D1 enables.
43
+ *
44
+ * Callers must bind `JSON.stringify(values)` for the returned placeholder.
45
+ */
46
+ function inJsonArray(column) {
47
+ return `${column} IN (SELECT value FROM json_each(?))`;
48
+ }
35
49
  function deserializeValue(value, type) {
36
50
  if (value === null || value === void 0) return null;
37
51
  if (type === "date" && typeof value === "string") return new Date(value);
@@ -1650,10 +1664,9 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1650
1664
  const resourceCondition = resourceId ? ` AND resourceId = ?` : "";
1651
1665
  const targetIds = include.map((inc) => inc.id).filter(Boolean);
1652
1666
  if (targetIds.length === 0) return null;
1653
- const idPlaceholders = targetIds.map(() => "?").join(", ");
1654
1667
  const targetResult = await this.#db.executeQuery({
1655
- sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE id IN (${idPlaceholders})${resourceCondition}`,
1656
- params: resourceId ? [...targetIds, resourceId] : targetIds
1668
+ sql: `SELECT id, thread_id, createdAt FROM ${tableName} WHERE ${inJsonArray("id")}${resourceCondition}`,
1669
+ params: resourceId ? [JSON.stringify(targetIds), resourceId] : [JSON.stringify(targetIds)]
1657
1670
  });
1658
1671
  if (!Array.isArray(targetResult) || targetResult.length === 0) return null;
1659
1672
  const targetMap = new Map(targetResult.map((r) => [r.id, {
@@ -1735,7 +1748,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1735
1748
  "createdAt",
1736
1749
  "thread_id AS threadId",
1737
1750
  "resourceId"
1738
- ]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
1751
+ ]).from(fullTableName).where(inJsonArray("id"), JSON.stringify(messageIds));
1739
1752
  query.orderBy("createdAt", "DESC");
1740
1753
  const { sql, params } = query.build();
1741
1754
  const result = await this.#db.executeQuery({
@@ -1786,13 +1799,12 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1786
1799
  const metadataFilter = (0, _mastra_core_storage.validateStorageMetadataFilter)(filter?.metadata);
1787
1800
  try {
1788
1801
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_MESSAGES);
1789
- const threadPlaceholders = threadIds.map(() => "?").join(", ");
1790
1802
  let query = `
1791
1803
  SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1792
1804
  FROM ${fullTableName}
1793
- WHERE thread_id IN (${threadPlaceholders})
1805
+ WHERE ${inJsonArray("thread_id")}
1794
1806
  `;
1795
- const queryParams = [...threadIds];
1807
+ const queryParams = [JSON.stringify(threadIds)];
1796
1808
  if (resourceId) {
1797
1809
  query += ` AND resourceId = ?`;
1798
1810
  queryParams.push(resourceId);
@@ -1857,8 +1869,8 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1857
1869
  return processedMsg;
1858
1870
  });
1859
1871
  const paginatedCount = paginatedMessages.length;
1860
- let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id IN (${threadPlaceholders})`;
1861
- const countParams = [...threadIds];
1872
+ let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE ${inJsonArray("thread_id")}`;
1873
+ const countParams = [JSON.stringify(threadIds)];
1862
1874
  if (resourceId) {
1863
1875
  countQuery += ` AND resourceId = ?`;
1864
1876
  countParams.push(resourceId);
@@ -1911,7 +1923,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1911
1923
  total,
1912
1924
  page,
1913
1925
  perPage: perPageForResponse,
1914
- hasMore: metadataFilter ? perPageInput !== false && offset + paginatedCount < total : perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total
1926
+ hasMore: metadataFilter || dateRange?.start || dateRange?.end ? perPageInput !== false && offset + paginatedCount < total : perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total
1915
1927
  };
1916
1928
  } catch (error) {
1917
1929
  if (error instanceof _mastra_core_error.MastraError && error.category === _mastra_core_error.ErrorCategory.USER) throw error;
@@ -1942,10 +1954,10 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1942
1954
  const fullTableName = this.#db.getTableName(_mastra_core_storage.TABLE_MESSAGES);
1943
1955
  const threadsTableName = this.#db.getTableName(_mastra_core_storage.TABLE_THREADS);
1944
1956
  try {
1945
- const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE id IN (${messageIds.map(() => "?").join(",")})`;
1957
+ const selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${fullTableName} WHERE ${inJsonArray("id")}`;
1946
1958
  const existingMessages = await this.#db.executeQuery({
1947
1959
  sql: selectQuery,
1948
- params: messageIds
1960
+ params: [JSON.stringify(messageIds)]
1949
1961
  });
1950
1962
  if (existingMessages.length === 0) return [];
1951
1963
  const parsedExistingMessages = existingMessages.map((msg) => {
@@ -1996,10 +2008,10 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
1996
2008
  }
1997
2009
  for (const query of updateQueries) await executeFenced(this.#db, check, query);
1998
2010
  if (threadIdsToUpdate.size > 0) {
1999
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${Array.from(threadIdsToUpdate).map(() => "?").join(",")})${guardSql}`;
2011
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE ${inJsonArray("id")}${guardSql}`;
2000
2012
  const threadUpdateParams = [
2001
2013
  (/* @__PURE__ */ new Date()).toISOString(),
2002
- ...Array.from(threadIdsToUpdate),
2014
+ JSON.stringify(Array.from(threadIdsToUpdate)),
2003
2015
  ...guardParams
2004
2016
  ];
2005
2017
  await executeFenced(this.#db, check, {
@@ -2009,7 +2021,7 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
2009
2021
  }
2010
2022
  return (await this.#db.executeQuery({
2011
2023
  sql: selectQuery,
2012
- params: messageIds
2024
+ params: [JSON.stringify(messageIds)]
2013
2025
  })).map((message) => {
2014
2026
  if (typeof message.content === "string") try {
2015
2027
  message.content = JSON.parse(message.content);
@@ -2033,20 +2045,19 @@ var MemoryStorageD1 = class MemoryStorageD1 extends _mastra_core_storage.MemoryS
2033
2045
  const check = this.#runFenceCheck(options?.fence, "deleteMessages");
2034
2046
  const guard = runFenceGuard(check);
2035
2047
  try {
2036
- const placeholders = messageIds.map(() => "?").join(",");
2037
- const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE id IN (${placeholders})`;
2048
+ const selectQuery = `SELECT DISTINCT thread_id FROM ${fullTableName} WHERE ${inJsonArray("id")}`;
2038
2049
  const threadIds = (await this.#db.executeQuery({
2039
2050
  sql: selectQuery,
2040
- params: messageIds
2051
+ params: [JSON.stringify(messageIds)]
2041
2052
  })).map((r) => r.thread_id).filter(Boolean);
2042
- const deleteQuery = createSqlBuilder().delete(fullTableName).where(`id IN (${placeholders})`, ...messageIds);
2053
+ const deleteQuery = createSqlBuilder().delete(fullTableName).where(inJsonArray("id"), JSON.stringify(messageIds));
2043
2054
  if (guard) deleteQuery.andWhere(guard.sql, ...guard.params);
2044
2055
  await executeFenced(this.#db, check, deleteQuery.build());
2045
2056
  if (threadIds.length > 0) {
2046
- const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE id IN (${threadIds.map(() => "?").join(",")})${guard ? ` AND ${guard.sql}` : ""}`;
2057
+ const threadUpdateQuery = `UPDATE ${threadsTableName} SET updatedAt = ? WHERE ${inJsonArray("id")}${guard ? ` AND ${guard.sql}` : ""}`;
2047
2058
  const threadUpdateParams = [
2048
2059
  (/* @__PURE__ */ new Date()).toISOString(),
2049
- ...threadIds,
2060
+ JSON.stringify(threadIds),
2050
2061
  ...guard?.params ?? []
2051
2062
  ];
2052
2063
  await executeFenced(this.#db, check, {