@mastra/cloudflare-d1 0.10.2-alpha.0 → 0.10.2-alpha.1

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.
@@ -15,30 +15,6 @@ import type { WorkflowRunState } from '@mastra/core';
15
15
 
16
16
  export declare const checkWorkflowSnapshot: (snapshot: WorkflowRunState | string, stepId: string, status: string) => void;
17
17
 
18
- export declare const createSampleMessage: (threadId: string, parts?: MastraMessageV2["content"]["parts"], createdAt?: Date) => MastraMessageV2;
19
-
20
- export declare const createSampleThread: () => {
21
- id: string;
22
- resourceId: string;
23
- title: string;
24
- createdAt: Date;
25
- updatedAt: Date;
26
- metadata: {
27
- key: string;
28
- };
29
- };
30
-
31
- export declare const createSampleThreadWithParams: (threadId: string, resourceId: string, createdAt: Date, updatedAt: Date) => {
32
- id: string;
33
- resourceId: string;
34
- title: string;
35
- createdAt: Date;
36
- updatedAt: Date;
37
- metadata: {
38
- key: string;
39
- };
40
- };
41
-
42
18
  export declare const createSampleTrace: (name: string, scope?: string, attributes?: Record<string, string>) => {
43
19
  id: string;
44
20
  parentSpanId: string;
@@ -56,12 +32,6 @@ export declare const createSampleTrace: (name: string, scope?: string, attribute
56
32
  createdAt: string;
57
33
  };
58
34
 
59
- export declare const createSampleWorkflowSnapshot: (threadId: string, status: string, createdAt?: Date) => {
60
- snapshot: WorkflowRunState;
61
- runId: string;
62
- stepId: string;
63
- };
64
-
65
35
  export declare function createSqlBuilder(): SqlBuilder;
66
36
 
67
37
  /**
@@ -101,15 +71,25 @@ declare class D1Store extends MastraStorage {
101
71
  * @returns Query results as an array or a single object if first=true
102
72
  */
103
73
  private executeQuery;
104
- private getSqlType;
105
- private ensureDate;
106
- private serializeDate;
74
+ private getTableColumns;
107
75
  private serializeValue;
108
76
  private deserializeValue;
77
+ protected getSqlType(type: StorageColumn['type']): string;
109
78
  createTable({ tableName, schema, }: {
110
79
  tableName: TABLE_NAMES;
111
80
  schema: Record<string, StorageColumn>;
112
81
  }): Promise<void>;
82
+ /**
83
+ * Alters table schema to add columns if they don't exist
84
+ * @param tableName Name of the table
85
+ * @param schema Schema of the table
86
+ * @param ifNotExists Array of column names to add if they don't exist
87
+ */
88
+ alterTable({ tableName, schema, ifNotExists, }: {
89
+ tableName: TABLE_NAMES;
90
+ schema: Record<string, StorageColumn>;
91
+ ifNotExists: string[];
92
+ }): Promise<void>;
113
93
  clearTable({ tableName }: {
114
94
  tableName: TABLE_NAMES;
115
95
  }): Promise<void>;
@@ -15,30 +15,6 @@ import type { WorkflowRunState } from '@mastra/core';
15
15
 
16
16
  export declare const checkWorkflowSnapshot: (snapshot: WorkflowRunState | string, stepId: string, status: string) => void;
17
17
 
18
- export declare const createSampleMessage: (threadId: string, parts?: MastraMessageV2["content"]["parts"], createdAt?: Date) => MastraMessageV2;
19
-
20
- export declare const createSampleThread: () => {
21
- id: string;
22
- resourceId: string;
23
- title: string;
24
- createdAt: Date;
25
- updatedAt: Date;
26
- metadata: {
27
- key: string;
28
- };
29
- };
30
-
31
- export declare const createSampleThreadWithParams: (threadId: string, resourceId: string, createdAt: Date, updatedAt: Date) => {
32
- id: string;
33
- resourceId: string;
34
- title: string;
35
- createdAt: Date;
36
- updatedAt: Date;
37
- metadata: {
38
- key: string;
39
- };
40
- };
41
-
42
18
  export declare const createSampleTrace: (name: string, scope?: string, attributes?: Record<string, string>) => {
43
19
  id: string;
44
20
  parentSpanId: string;
@@ -56,12 +32,6 @@ export declare const createSampleTrace: (name: string, scope?: string, attribute
56
32
  createdAt: string;
57
33
  };
58
34
 
59
- export declare const createSampleWorkflowSnapshot: (threadId: string, status: string, createdAt?: Date) => {
60
- snapshot: WorkflowRunState;
61
- runId: string;
62
- stepId: string;
63
- };
64
-
65
35
  export declare function createSqlBuilder(): SqlBuilder;
66
36
 
67
37
  /**
@@ -101,15 +71,25 @@ declare class D1Store extends MastraStorage {
101
71
  * @returns Query results as an array or a single object if first=true
102
72
  */
103
73
  private executeQuery;
104
- private getSqlType;
105
- private ensureDate;
106
- private serializeDate;
74
+ private getTableColumns;
107
75
  private serializeValue;
108
76
  private deserializeValue;
77
+ protected getSqlType(type: StorageColumn['type']): string;
109
78
  createTable({ tableName, schema, }: {
110
79
  tableName: TABLE_NAMES;
111
80
  schema: Record<string, StorageColumn>;
112
81
  }): Promise<void>;
82
+ /**
83
+ * Alters table schema to add columns if they don't exist
84
+ * @param tableName Name of the table
85
+ * @param schema Schema of the table
86
+ * @param ifNotExists Array of column names to add if they don't exist
87
+ */
88
+ alterTable({ tableName, schema, ifNotExists, }: {
89
+ tableName: TABLE_NAMES;
90
+ schema: Record<string, StorageColumn>;
91
+ ifNotExists: string[];
92
+ }): Promise<void>;
113
93
  clearTable({ tableName }: {
114
94
  tableName: TABLE_NAMES;
115
95
  }): Promise<void>;
package/dist/index.cjs CHANGED
@@ -389,34 +389,25 @@ var D1Store = class extends storage.MastraStorage {
389
389
  throw new Error(`D1 query error: ${error.message}`);
390
390
  }
391
391
  }
392
- // Helper to convert storage type to SQL type
393
- getSqlType(type) {
394
- switch (type) {
395
- case "text":
396
- return "TEXT";
397
- case "timestamp":
398
- return "TIMESTAMP";
399
- case "integer":
400
- return "INTEGER";
401
- case "bigint":
402
- return "INTEGER";
403
- // SQLite doesn't have a separate BIGINT type
404
- case "jsonb":
405
- return "TEXT";
406
- // Store JSON as TEXT in SQLite
407
- default:
408
- return "TEXT";
392
+ // Helper to get existing table columns
393
+ async getTableColumns(tableName) {
394
+ try {
395
+ const sql = `PRAGMA table_info(${tableName})`;
396
+ const result = await this.executeQuery({ sql, params: [] });
397
+ if (!result || !Array.isArray(result)) {
398
+ return [];
399
+ }
400
+ return result.map((row) => ({
401
+ name: row.name,
402
+ type: row.type
403
+ }));
404
+ } catch (error) {
405
+ this.logger.error(`Error getting table columns for ${tableName}:`, {
406
+ message: error instanceof Error ? error.message : String(error)
407
+ });
408
+ return [];
409
409
  }
410
410
  }
411
- ensureDate(date) {
412
- if (!date) return void 0;
413
- return date instanceof Date ? date : new Date(date);
414
- }
415
- serializeDate(date) {
416
- if (!date) return void 0;
417
- const dateObj = this.ensureDate(date);
418
- return dateObj?.toISOString();
419
- }
420
411
  // Helper to serialize objects to JSON strings
421
412
  serializeValue(value) {
422
413
  if (value === null || value === void 0) return null;
@@ -450,6 +441,18 @@ var D1Store = class extends storage.MastraStorage {
450
441
  }
451
442
  return value;
452
443
  }
444
+ getSqlType(type) {
445
+ switch (type) {
446
+ case "bigint":
447
+ return "INTEGER";
448
+ // SQLite uses INTEGER for all integer sizes
449
+ case "jsonb":
450
+ return "TEXT";
451
+ // Store JSON as TEXT in SQLite
452
+ default:
453
+ return super.getSqlType(type);
454
+ }
455
+ }
453
456
  async createTable({
454
457
  tableName,
455
458
  schema
@@ -477,6 +480,39 @@ var D1Store = class extends storage.MastraStorage {
477
480
  throw new Error(`Failed to create table ${fullTableName}: ${error}`);
478
481
  }
479
482
  }
483
+ /**
484
+ * Alters table schema to add columns if they don't exist
485
+ * @param tableName Name of the table
486
+ * @param schema Schema of the table
487
+ * @param ifNotExists Array of column names to add if they don't exist
488
+ */
489
+ async alterTable({
490
+ tableName,
491
+ schema,
492
+ ifNotExists
493
+ }) {
494
+ const fullTableName = this.getTableName(tableName);
495
+ try {
496
+ const existingColumns = await this.getTableColumns(fullTableName);
497
+ const existingColumnNames = new Set(existingColumns.map((col) => col.name.toLowerCase()));
498
+ for (const columnName of ifNotExists) {
499
+ if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
500
+ const columnDef = schema[columnName];
501
+ const sqlType = this.getSqlType(columnDef.type);
502
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
503
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
504
+ const alterSql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${nullable} ${defaultValue}`.trim();
505
+ await this.executeQuery({ sql: alterSql, params: [] });
506
+ this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
507
+ }
508
+ }
509
+ } catch (error) {
510
+ this.logger.error(`Error altering table ${fullTableName}:`, {
511
+ message: error instanceof Error ? error.message : String(error)
512
+ });
513
+ throw new Error(`Failed to alter table ${fullTableName}: ${error}`);
514
+ }
515
+ }
480
516
  async clearTable({ tableName }) {
481
517
  const fullTableName = this.getTableName(tableName);
482
518
  try {
@@ -713,7 +749,8 @@ var D1Store = class extends storage.MastraStorage {
713
749
  content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
714
750
  createdAt: createdAt.toISOString(),
715
751
  role: message.role,
716
- type: message.type || "v2"
752
+ type: message.type || "v2",
753
+ resourceId: message.resourceId
717
754
  };
718
755
  });
719
756
  await this.batchInsert({
package/dist/index.js CHANGED
@@ -383,34 +383,25 @@ var D1Store = class extends MastraStorage {
383
383
  throw new Error(`D1 query error: ${error.message}`);
384
384
  }
385
385
  }
386
- // Helper to convert storage type to SQL type
387
- getSqlType(type) {
388
- switch (type) {
389
- case "text":
390
- return "TEXT";
391
- case "timestamp":
392
- return "TIMESTAMP";
393
- case "integer":
394
- return "INTEGER";
395
- case "bigint":
396
- return "INTEGER";
397
- // SQLite doesn't have a separate BIGINT type
398
- case "jsonb":
399
- return "TEXT";
400
- // Store JSON as TEXT in SQLite
401
- default:
402
- return "TEXT";
386
+ // Helper to get existing table columns
387
+ async getTableColumns(tableName) {
388
+ try {
389
+ const sql = `PRAGMA table_info(${tableName})`;
390
+ const result = await this.executeQuery({ sql, params: [] });
391
+ if (!result || !Array.isArray(result)) {
392
+ return [];
393
+ }
394
+ return result.map((row) => ({
395
+ name: row.name,
396
+ type: row.type
397
+ }));
398
+ } catch (error) {
399
+ this.logger.error(`Error getting table columns for ${tableName}:`, {
400
+ message: error instanceof Error ? error.message : String(error)
401
+ });
402
+ return [];
403
403
  }
404
404
  }
405
- ensureDate(date) {
406
- if (!date) return void 0;
407
- return date instanceof Date ? date : new Date(date);
408
- }
409
- serializeDate(date) {
410
- if (!date) return void 0;
411
- const dateObj = this.ensureDate(date);
412
- return dateObj?.toISOString();
413
- }
414
405
  // Helper to serialize objects to JSON strings
415
406
  serializeValue(value) {
416
407
  if (value === null || value === void 0) return null;
@@ -444,6 +435,18 @@ var D1Store = class extends MastraStorage {
444
435
  }
445
436
  return value;
446
437
  }
438
+ getSqlType(type) {
439
+ switch (type) {
440
+ case "bigint":
441
+ return "INTEGER";
442
+ // SQLite uses INTEGER for all integer sizes
443
+ case "jsonb":
444
+ return "TEXT";
445
+ // Store JSON as TEXT in SQLite
446
+ default:
447
+ return super.getSqlType(type);
448
+ }
449
+ }
447
450
  async createTable({
448
451
  tableName,
449
452
  schema
@@ -471,6 +474,39 @@ var D1Store = class extends MastraStorage {
471
474
  throw new Error(`Failed to create table ${fullTableName}: ${error}`);
472
475
  }
473
476
  }
477
+ /**
478
+ * Alters table schema to add columns if they don't exist
479
+ * @param tableName Name of the table
480
+ * @param schema Schema of the table
481
+ * @param ifNotExists Array of column names to add if they don't exist
482
+ */
483
+ async alterTable({
484
+ tableName,
485
+ schema,
486
+ ifNotExists
487
+ }) {
488
+ const fullTableName = this.getTableName(tableName);
489
+ try {
490
+ const existingColumns = await this.getTableColumns(fullTableName);
491
+ const existingColumnNames = new Set(existingColumns.map((col) => col.name.toLowerCase()));
492
+ for (const columnName of ifNotExists) {
493
+ if (!existingColumnNames.has(columnName.toLowerCase()) && schema[columnName]) {
494
+ const columnDef = schema[columnName];
495
+ const sqlType = this.getSqlType(columnDef.type);
496
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
497
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
498
+ const alterSql = `ALTER TABLE ${fullTableName} ADD COLUMN ${columnName} ${sqlType} ${nullable} ${defaultValue}`.trim();
499
+ await this.executeQuery({ sql: alterSql, params: [] });
500
+ this.logger.debug(`Added column ${columnName} to table ${fullTableName}`);
501
+ }
502
+ }
503
+ } catch (error) {
504
+ this.logger.error(`Error altering table ${fullTableName}:`, {
505
+ message: error instanceof Error ? error.message : String(error)
506
+ });
507
+ throw new Error(`Failed to alter table ${fullTableName}: ${error}`);
508
+ }
509
+ }
474
510
  async clearTable({ tableName }) {
475
511
  const fullTableName = this.getTableName(tableName);
476
512
  try {
@@ -707,7 +743,8 @@ var D1Store = class extends MastraStorage {
707
743
  content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
708
744
  createdAt: createdAt.toISOString(),
709
745
  role: message.role,
710
- type: message.type || "v2"
746
+ type: message.type || "v2",
747
+ resourceId: message.resourceId
711
748
  };
712
749
  });
713
750
  await this.batchInsert({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/cloudflare-d1",
3
- "version": "0.10.2-alpha.0",
3
+ "version": "0.10.2-alpha.1",
4
4
  "description": "D1 provider for Mastra - includes db storage capabilities",
5
5
  "type": "module",
6
6
  "files": [
@@ -22,21 +22,21 @@
22
22
  "./package.json": "./package.json"
23
23
  },
24
24
  "dependencies": {
25
- "cloudflare": "^4.1.0"
25
+ "cloudflare": "^4.3.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@cloudflare/workers-types": "^4.20250417.0",
28
+ "@cloudflare/workers-types": "^4.20250607.0",
29
29
  "@microsoft/api-extractor": "^7.52.8",
30
30
  "@types/node": "^20.17.57",
31
31
  "dotenv": "^16.5.0",
32
32
  "eslint": "^9.28.0",
33
- "miniflare": "^4.20250410.1",
33
+ "miniflare": "^4.20250525.1",
34
34
  "tsup": "^8.5.0",
35
35
  "typescript": "^5.8.2",
36
- "vitest": "^3.1.2",
36
+ "vitest": "^3.2.2",
37
37
  "@internal/lint": "0.0.10",
38
- "@internal/storage-test-utils": "0.0.6",
39
- "@mastra/core": "0.10.4-alpha.0"
38
+ "@mastra/core": "0.10.4-alpha.1",
39
+ "@internal/storage-test-utils": "0.0.6"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@mastra/core": "^0.10.2-alpha.0"