@langchain/google-cloud-sql-pg 0.0.2 → 1.0.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +6 -6
  3. package/README.md +1 -1
  4. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  5. package/dist/chat_message_history.cjs +104 -137
  6. package/dist/chat_message_history.cjs.map +1 -0
  7. package/dist/chat_message_history.d.cts +57 -0
  8. package/dist/chat_message_history.d.ts +53 -43
  9. package/dist/chat_message_history.js +103 -133
  10. package/dist/chat_message_history.js.map +1 -0
  11. package/dist/engine.cjs +188 -242
  12. package/dist/engine.cjs.map +1 -0
  13. package/dist/engine.d.cts +138 -0
  14. package/dist/engine.d.ts +102 -80
  15. package/dist/engine.js +186 -234
  16. package/dist/engine.js.map +1 -0
  17. package/dist/index.cjs +21 -20
  18. package/dist/index.d.cts +6 -0
  19. package/dist/index.d.ts +6 -4
  20. package/dist/index.js +7 -4
  21. package/dist/indexes.cjs +96 -168
  22. package/dist/indexes.cjs.map +1 -0
  23. package/dist/indexes.d.cts +68 -0
  24. package/dist/indexes.d.ts +50 -47
  25. package/dist/indexes.js +90 -161
  26. package/dist/indexes.js.map +1 -0
  27. package/dist/loader.cjs +159 -242
  28. package/dist/loader.cjs.map +1 -0
  29. package/dist/loader.d.cts +101 -0
  30. package/dist/loader.d.ts +40 -26
  31. package/dist/loader.js +157 -237
  32. package/dist/loader.js.map +1 -0
  33. package/dist/utils/utils.cjs +36 -65
  34. package/dist/utils/utils.cjs.map +1 -0
  35. package/dist/utils/utils.js +36 -62
  36. package/dist/utils/utils.js.map +1 -0
  37. package/dist/vectorstore.cjs +438 -593
  38. package/dist/vectorstore.cjs.map +1 -0
  39. package/dist/vectorstore.d.cts +300 -0
  40. package/dist/vectorstore.d.ts +147 -130
  41. package/dist/vectorstore.js +436 -588
  42. package/dist/vectorstore.js.map +1 -0
  43. package/package.json +41 -48
  44. package/dist/utils/utils.d.ts +0 -22
  45. package/index.cjs +0 -1
  46. package/index.d.cts +0 -1
  47. package/index.d.ts +0 -1
  48. package/index.js +0 -1
package/dist/engine.d.ts CHANGED
@@ -1,27 +1,30 @@
1
1
  import { Connector, IpAddressTypes } from "@google-cloud/cloud-sql-connector";
2
2
  import knex from "knex";
3
- export interface PostgresEngineArgs {
4
- ipType?: IpAddressTypes;
5
- user?: string;
6
- password?: string;
7
- iamAccountEmail?: string;
3
+
4
+ //#region src/engine.d.ts
5
+ interface PostgresEngineArgs {
6
+ ipType?: IpAddressTypes;
7
+ user?: string;
8
+ password?: string;
9
+ iamAccountEmail?: string;
8
10
  }
9
- export interface VectorStoreTableArgs {
10
- schemaName?: string;
11
- contentColumn?: string;
12
- embeddingColumn?: string;
13
- metadataColumns?: Column[];
14
- metadataJsonColumn?: string;
15
- idColumn?: string | Column;
16
- overwriteExisting?: boolean;
17
- storeMetadata?: boolean;
11
+ interface VectorStoreTableArgs {
12
+ schemaName?: string;
13
+ contentColumn?: string;
14
+ embeddingColumn?: string;
15
+ embeddingColumnType?: "vector" | "halfvec" | "bit" | "sparsevec";
16
+ metadataColumns?: Column[];
17
+ metadataJsonColumn?: string;
18
+ idColumn?: string | Column;
19
+ overwriteExisting?: boolean;
20
+ storeMetadata?: boolean;
18
21
  }
19
- export declare class Column {
20
- name: string;
21
- dataType: string;
22
- nullable: boolean;
23
- constructor(name: string, dataType: string, nullable?: boolean);
24
- private postInitilization;
22
+ declare class Column {
23
+ name: string;
24
+ dataType: string;
25
+ nullable: boolean;
26
+ constructor(name: string, dataType: string, nullable?: boolean);
27
+ private postInitilization;
25
28
  }
26
29
  /**
27
30
  * Cloud SQL shared connection pool
@@ -53,64 +56,83 @@ export declare class Column {
53
56
  * <br />
54
57
  *
55
58
  */
56
- export declare class PostgresEngine {
57
- private static _createKey;
58
- pool: knex.Knex;
59
- static connector: Connector;
60
- constructor(key: symbol, pool: knex.Knex);
61
- /**
62
- * @param projectId Required - GCP Project ID
63
- * @param region Required - Postgres Instance Region
64
- * @param instance Required - Postgres Instance name
65
- * @param database Required - Database name
66
- * @param ipType Optional - IP address type. Defaults to IPAddressType.PUBLIC
67
- * @param user Optional - Postgres user name. Defaults to undefined
68
- * @param password Optional - Postgres user password. Defaults to undefined
69
- * @param iamAccountEmail Optional - IAM service account email. Defaults to undefined
70
- * @returns PostgresEngine instance
71
- */
72
- static fromInstance(projectId: string, region: string, instance: string, database: string, { ipType, user, password, iamAccountEmail, }?: PostgresEngineArgs): Promise<PostgresEngine>;
73
- /**
74
- * Create a PostgresEngine instance from an Knex instance.
75
- *
76
- * @param engine knex instance
77
- * @returns PostgresEngine instance from a knex instance
78
- */
79
- static fromPool(engine: knex.Knex): Promise<PostgresEngine>;
80
- /**
81
- * Create a PostgresEngine instance from arguments.
82
- *
83
- * @param url URL use to connect to a database
84
- * @param poolConfig Optional - Configuration pool to use in the Knex configuration
85
- * @returns PostgresEngine instance
86
- */
87
- static fromConnectionString(url: string | knex.Knex.StaticConnectionConfig, poolConfig?: knex.Knex.PoolConfig): Promise<PostgresEngine>;
88
- /**
89
- * Create a table for saving of vectors to be used with PostgresVectorStore.
90
- *
91
- * @param tableName Postgres database table name. Parameter is not escaped. Do not use with end user input.
92
- * @param vectorSize Vector size for the embedding model to be used.
93
- * @param schemaName The schema name to store Postgres database table. Default: "public". Parameter is not escaped. Do not use with end user input.
94
- * @param contentColumn Name of the column to store document content. Default: "content".
95
- * @param embeddingColumn Name of the column to store vector embeddings. Default: "embedding".
96
- * @param metadataColumns Optional - A list of Columns to create for custom metadata. Default: [].
97
- * @param metadataJsonColumn Optional - The column to store extra metadata in JSON format. Default: "langchain_metadata".
98
- * @param idColumn Optional - Column to store ids. Default: "langchain_id" column name with data type UUID.
99
- * @param overwriteExisting Whether to drop existing table. Default: False.
100
- * @param storeMetadata Whether to store metadata in the table. Default: True.
101
- */
102
- initVectorstoreTable(tableName: string, vectorSize: number, { schemaName, contentColumn, embeddingColumn, metadataColumns, metadataJsonColumn, idColumn, overwriteExisting, storeMetadata, }?: VectorStoreTableArgs): Promise<void>;
103
- /**
104
- * Create a Cloud SQL table to store chat history.
105
- *
106
- * @param tableName Table name to store chat history
107
- * @param schemaName Schema name to store chat history table
108
- */
109
- initChatHistoryTable(tableName: string, schemaName?: string): Promise<void>;
110
- /**
111
- * Dispose of connection pool
112
- */
113
- closeConnection(): Promise<void>;
114
- testConnection(): knex.Knex.Raw<any>;
59
+ declare class PostgresEngine {
60
+ private static _createKey;
61
+ pool: knex.Knex;
62
+ static connector: Connector;
63
+ constructor(key: symbol, pool: knex.Knex);
64
+ /**
65
+ * @param projectId Required - GCP Project ID
66
+ * @param region Required - Postgres Instance Region
67
+ * @param instance Required - Postgres Instance name
68
+ * @param database Required - Database name
69
+ * @param ipType Optional - IP address type. Defaults to IPAddressType.PUBLIC
70
+ * @param user Optional - Postgres user name. Defaults to undefined
71
+ * @param password Optional - Postgres user password. Defaults to undefined
72
+ * @param iamAccountEmail Optional - IAM service account email. Defaults to undefined
73
+ * @returns PostgresEngine instance
74
+ */
75
+ static fromInstance(projectId: string, region: string, instance: string, database: string, {
76
+ ipType,
77
+ user,
78
+ password,
79
+ iamAccountEmail
80
+ }?: PostgresEngineArgs): Promise<PostgresEngine>;
81
+ /**
82
+ * Create a PostgresEngine instance from an Knex instance.
83
+ *
84
+ * @param engine knex instance
85
+ * @returns PostgresEngine instance from a knex instance
86
+ */
87
+ static fromPool(engine: knex.Knex): Promise<PostgresEngine>;
88
+ /**
89
+ * Create a PostgresEngine instance from arguments.
90
+ *
91
+ * @param url URL use to connect to a database
92
+ * @param poolConfig Optional - Configuration pool to use in the Knex configuration
93
+ * @returns PostgresEngine instance
94
+ */
95
+ static fromConnectionString(url: string | knex.Knex.StaticConnectionConfig, poolConfig?: knex.Knex.PoolConfig): Promise<PostgresEngine>;
96
+ /**
97
+ * Create a table for saving of vectors to be used with PostgresVectorStore.
98
+ *
99
+ * @param tableName Postgres database table name. Parameter is not escaped. Do not use with end user input.
100
+ * @param vectorSize Vector size for the embedding model to be used.
101
+ * @param schemaName The schema name to store Postgres database table. Default: "public". Parameter is not escaped. Do not use with end user input.
102
+ * @param contentColumn Name of the column to store document content. Default: "content".
103
+ * @param embeddingColumn Name of the column to store vector embeddings. Default: "embedding".
104
+ * @param embeddingColumnType Type of the embedding column ("vector" | "halfvec" | "bit" | "sparsevec"). Default: "vector". More info on HNSW-supported types: https://github.com/pgvector/pgvector#hnsw
105
+ * @param metadataColumns Optional - A list of Columns to create for custom metadata. Default: [].
106
+ * @param metadataJsonColumn Optional - The column to store extra metadata in JSON format. Default: "langchain_metadata".
107
+ * @param idColumn Optional - Column to store ids. Default: "langchain_id" column name with data type UUID.
108
+ * @param overwriteExisting Whether to drop existing table. Default: False.
109
+ * @param storeMetadata Whether to store metadata in the table. Default: True.
110
+ */
111
+ initVectorstoreTable(tableName: string, vectorSize: number, {
112
+ schemaName,
113
+ contentColumn,
114
+ embeddingColumn,
115
+ embeddingColumnType,
116
+ metadataColumns,
117
+ metadataJsonColumn,
118
+ idColumn,
119
+ overwriteExisting,
120
+ storeMetadata
121
+ }?: VectorStoreTableArgs): Promise<void>;
122
+ /**
123
+ * Create a Cloud SQL table to store chat history.
124
+ *
125
+ * @param tableName Table name to store chat history
126
+ * @param schemaName Schema name to store chat history table
127
+ */
128
+ initChatHistoryTable(tableName: string, schemaName?: string): Promise<void>;
129
+ /**
130
+ * Dispose of connection pool
131
+ */
132
+ closeConnection(): Promise<void>;
133
+ // Just to test the connection to the database
134
+ testConnection(): knex.Knex.Raw<any>;
115
135
  }
116
- export default PostgresEngine;
136
+ //#endregion
137
+ export { Column, PostgresEngine, PostgresEngineArgs, VectorStoreTableArgs };
138
+ //# sourceMappingURL=engine.d.ts.map
package/dist/engine.js CHANGED
@@ -1,244 +1,196 @@
1
- import { AuthTypes, Connector, IpAddressTypes, } from "@google-cloud/cloud-sql-connector";
1
+ import { getIAMPrincipalEmail } from "./utils/utils.js";
2
+ import { AuthTypes, Connector, IpAddressTypes } from "@google-cloud/cloud-sql-connector";
2
3
  import { GoogleAuth } from "google-auth-library";
3
4
  import knex from "knex";
4
- import { getIAMPrincipalEmail } from "./utils/utils.js";
5
- export class Column {
6
- constructor(name, dataType, nullable = true) {
7
- Object.defineProperty(this, "name", {
8
- enumerable: true,
9
- configurable: true,
10
- writable: true,
11
- value: void 0
12
- });
13
- Object.defineProperty(this, "dataType", {
14
- enumerable: true,
15
- configurable: true,
16
- writable: true,
17
- value: void 0
18
- });
19
- Object.defineProperty(this, "nullable", {
20
- enumerable: true,
21
- configurable: true,
22
- writable: true,
23
- value: void 0
24
- });
25
- this.name = name;
26
- this.dataType = dataType;
27
- this.nullable = nullable;
28
- this.postInitilization();
29
- }
30
- postInitilization() {
31
- if (typeof this.name !== "string") {
32
- throw Error("Column name must be type string");
33
- }
34
- if (typeof this.dataType !== "string") {
35
- throw Error("Column data_type must be type string");
36
- }
37
- }
38
- }
5
+
6
+ //#region src/engine.ts
7
+ var Column = class {
8
+ name;
9
+ dataType;
10
+ nullable;
11
+ constructor(name, dataType, nullable = true) {
12
+ this.name = name;
13
+ this.dataType = dataType;
14
+ this.nullable = nullable;
15
+ this.postInitilization();
16
+ }
17
+ postInitilization() {
18
+ if (typeof this.name !== "string") throw Error("Column name must be type string");
19
+ if (typeof this.dataType !== "string") throw Error("Column data_type must be type string");
20
+ }
21
+ };
39
22
  const USER_AGENT = "langchain-google-cloud-sql-pg-js";
40
23
  /**
41
- * Cloud SQL shared connection pool
42
- *
43
- * Setup:
44
- * Install `@langchain/google-cloud-sql-pg`
45
- *
46
- * <details open>
47
- * <summary><strong>Instantiate</strong></summary>
48
- *
49
- * ```typescript
50
- * import { Column, PostgresEngine, PostgresEngineArgs } from "@langchain/google-cloud-sql-pg";
51
- *
52
- * const pgArgs: PostgresEngineArgs = {
53
- * user: "db-user",
54
- * password: "password"
55
- *}
56
- *
57
- * const engine: PostgresEngine = await PostgresEngine.fromInstance(
58
- * "project-id",
59
- * "region",
60
- * "instance-name",
61
- * "database-name",
62
- * pgArgs
63
- * );
64
- * ```
65
- * </details>
66
- *
67
- * <br />
68
- *
69
- */
70
- export class PostgresEngine {
71
- constructor(key, pool) {
72
- Object.defineProperty(this, "pool", {
73
- enumerable: true,
74
- configurable: true,
75
- writable: true,
76
- value: void 0
77
- });
78
- if (key !== PostgresEngine._createKey) {
79
- throw Error("Only create class through 'create' method!");
80
- }
81
- this.pool = pool;
82
- }
83
- /**
84
- * @param projectId Required - GCP Project ID
85
- * @param region Required - Postgres Instance Region
86
- * @param instance Required - Postgres Instance name
87
- * @param database Required - Database name
88
- * @param ipType Optional - IP address type. Defaults to IPAddressType.PUBLIC
89
- * @param user Optional - Postgres user name. Defaults to undefined
90
- * @param password Optional - Postgres user password. Defaults to undefined
91
- * @param iamAccountEmail Optional - IAM service account email. Defaults to undefined
92
- * @returns PostgresEngine instance
93
- */
94
- static async fromInstance(projectId, region, instance, database, { ipType = IpAddressTypes.PUBLIC, user, password, iamAccountEmail, } = {}) {
95
- let dbUser;
96
- let enableIAMAuth;
97
- if ((!user && password) || (user && !password)) {
98
- // XOR for strings
99
- throw Error("Only one of 'user' or 'password' were specified. Either " +
100
- "both should be specified to use basic user/password " +
101
- "authentication or neither for IAM DB authentication.");
102
- }
103
- // User and password are given so we use the basic auth
104
- if (user !== undefined && password !== undefined) {
105
- enableIAMAuth = false;
106
- dbUser = user;
107
- }
108
- else {
109
- enableIAMAuth = true;
110
- if (iamAccountEmail !== undefined) {
111
- dbUser = iamAccountEmail;
112
- }
113
- else {
114
- // Get application default credentials
115
- const auth = new GoogleAuth({
116
- scopes: "https://www.googleapis.com/auth/cloud-platform",
117
- });
118
- // dbUser should be the iam principal email by passing the credentials obtained
119
- dbUser = await getIAMPrincipalEmail(auth);
120
- }
121
- }
122
- PostgresEngine.connector = new Connector({ userAgent: USER_AGENT });
123
- const clientOpts = await PostgresEngine.connector.getOptions({
124
- instanceConnectionName: `${projectId}:${region}:${instance}`,
125
- ipType,
126
- authType: enableIAMAuth ? AuthTypes.IAM : AuthTypes.PASSWORD,
127
- });
128
- const dbConfig = {
129
- client: "pg",
130
- connection: {
131
- ...clientOpts,
132
- ...(password ? { password } : {}),
133
- user: dbUser,
134
- database,
135
- },
136
- };
137
- const engine = knex(dbConfig);
138
- return new PostgresEngine(PostgresEngine._createKey, engine);
139
- }
140
- /**
141
- * Create a PostgresEngine instance from an Knex instance.
142
- *
143
- * @param engine knex instance
144
- * @returns PostgresEngine instance from a knex instance
145
- */
146
- static async fromPool(engine) {
147
- return new PostgresEngine(PostgresEngine._createKey, engine);
148
- }
149
- /**
150
- * Create a PostgresEngine instance from arguments.
151
- *
152
- * @param url URL use to connect to a database
153
- * @param poolConfig Optional - Configuration pool to use in the Knex configuration
154
- * @returns PostgresEngine instance
155
- */
156
- static async fromConnectionString(url, poolConfig) {
157
- const driver = "postgresql+asyncpg";
158
- if (typeof url === "string" && !url.startsWith(driver)) {
159
- throw Error("Driver must be type 'postgresql+asyncpg'");
160
- }
161
- const dbConfig = {
162
- client: "pg",
163
- connection: url,
164
- acquireConnectionTimeout: 1000000,
165
- pool: {
166
- ...poolConfig,
167
- acquireTimeoutMillis: 600000,
168
- },
169
- };
170
- const engine = knex(dbConfig);
171
- return new PostgresEngine(PostgresEngine._createKey, engine);
172
- }
173
- /**
174
- * Create a table for saving of vectors to be used with PostgresVectorStore.
175
- *
176
- * @param tableName Postgres database table name. Parameter is not escaped. Do not use with end user input.
177
- * @param vectorSize Vector size for the embedding model to be used.
178
- * @param schemaName The schema name to store Postgres database table. Default: "public". Parameter is not escaped. Do not use with end user input.
179
- * @param contentColumn Name of the column to store document content. Default: "content".
180
- * @param embeddingColumn Name of the column to store vector embeddings. Default: "embedding".
181
- * @param metadataColumns Optional - A list of Columns to create for custom metadata. Default: [].
182
- * @param metadataJsonColumn Optional - The column to store extra metadata in JSON format. Default: "langchain_metadata".
183
- * @param idColumn Optional - Column to store ids. Default: "langchain_id" column name with data type UUID.
184
- * @param overwriteExisting Whether to drop existing table. Default: False.
185
- * @param storeMetadata Whether to store metadata in the table. Default: True.
186
- */
187
- async initVectorstoreTable(tableName, vectorSize, { schemaName = "public", contentColumn = "content", embeddingColumn = "embedding", metadataColumns = [], metadataJsonColumn = "langchain_metadata", idColumn = "langchain_id", overwriteExisting = false, storeMetadata = true, } = {}) {
188
- await this.pool.raw("CREATE EXTENSION IF NOT EXISTS vector");
189
- if (overwriteExisting) {
190
- await this.pool.schema
191
- .withSchema(schemaName)
192
- .dropTableIfExists(tableName);
193
- }
194
- const idDataType = typeof idColumn === "string" ? "UUID" : idColumn.dataType;
195
- const idColumnName = typeof idColumn === "string" ? idColumn : idColumn.name;
196
- let query = `CREATE TABLE ${schemaName}.${tableName}(
24
+ * Cloud SQL shared connection pool
25
+ *
26
+ * Setup:
27
+ * Install `@langchain/google-cloud-sql-pg`
28
+ *
29
+ * <details open>
30
+ * <summary><strong>Instantiate</strong></summary>
31
+ *
32
+ * ```typescript
33
+ * import { Column, PostgresEngine, PostgresEngineArgs } from "@langchain/google-cloud-sql-pg";
34
+ *
35
+ * const pgArgs: PostgresEngineArgs = {
36
+ * user: "db-user",
37
+ * password: "password"
38
+ *}
39
+ *
40
+ * const engine: PostgresEngine = await PostgresEngine.fromInstance(
41
+ * "project-id",
42
+ * "region",
43
+ * "instance-name",
44
+ * "database-name",
45
+ * pgArgs
46
+ * );
47
+ * ```
48
+ * </details>
49
+ *
50
+ * <br />
51
+ *
52
+ */
53
+ var PostgresEngine = class PostgresEngine {
54
+ static _createKey = Symbol("key");
55
+ pool;
56
+ static connector;
57
+ constructor(key, pool) {
58
+ if (key !== PostgresEngine._createKey) throw Error("Only create class through 'create' method!");
59
+ this.pool = pool;
60
+ }
61
+ /**
62
+ * @param projectId Required - GCP Project ID
63
+ * @param region Required - Postgres Instance Region
64
+ * @param instance Required - Postgres Instance name
65
+ * @param database Required - Database name
66
+ * @param ipType Optional - IP address type. Defaults to IPAddressType.PUBLIC
67
+ * @param user Optional - Postgres user name. Defaults to undefined
68
+ * @param password Optional - Postgres user password. Defaults to undefined
69
+ * @param iamAccountEmail Optional - IAM service account email. Defaults to undefined
70
+ * @returns PostgresEngine instance
71
+ */
72
+ static async fromInstance(projectId, region, instance, database, { ipType = IpAddressTypes.PUBLIC, user, password, iamAccountEmail } = {}) {
73
+ let dbUser;
74
+ let enableIAMAuth;
75
+ if (!user && password || user && !password) throw Error("Only one of 'user' or 'password' were specified. Either both should be specified to use basic user/password authentication or neither for IAM DB authentication.");
76
+ if (user !== void 0 && password !== void 0) {
77
+ enableIAMAuth = false;
78
+ dbUser = user;
79
+ } else {
80
+ enableIAMAuth = true;
81
+ if (iamAccountEmail !== void 0) dbUser = iamAccountEmail;
82
+ else {
83
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
84
+ dbUser = await getIAMPrincipalEmail(auth);
85
+ }
86
+ }
87
+ PostgresEngine.connector = new Connector({ userAgent: USER_AGENT });
88
+ const clientOpts = await PostgresEngine.connector.getOptions({
89
+ instanceConnectionName: `${projectId}:${region}:${instance}`,
90
+ ipType,
91
+ authType: enableIAMAuth ? AuthTypes.IAM : AuthTypes.PASSWORD
92
+ });
93
+ const dbConfig = {
94
+ client: "pg",
95
+ connection: {
96
+ ...clientOpts,
97
+ ...password ? { password } : {},
98
+ user: dbUser,
99
+ database
100
+ }
101
+ };
102
+ const engine = knex(dbConfig);
103
+ return new PostgresEngine(PostgresEngine._createKey, engine);
104
+ }
105
+ /**
106
+ * Create a PostgresEngine instance from an Knex instance.
107
+ *
108
+ * @param engine knex instance
109
+ * @returns PostgresEngine instance from a knex instance
110
+ */
111
+ static async fromPool(engine) {
112
+ return new PostgresEngine(PostgresEngine._createKey, engine);
113
+ }
114
+ /**
115
+ * Create a PostgresEngine instance from arguments.
116
+ *
117
+ * @param url URL use to connect to a database
118
+ * @param poolConfig Optional - Configuration pool to use in the Knex configuration
119
+ * @returns PostgresEngine instance
120
+ */
121
+ static async fromConnectionString(url, poolConfig) {
122
+ const driver = "postgresql+asyncpg";
123
+ if (typeof url === "string" && !url.startsWith(driver)) throw Error("Driver must be type 'postgresql+asyncpg'");
124
+ const dbConfig = {
125
+ client: "pg",
126
+ connection: url,
127
+ acquireConnectionTimeout: 1e6,
128
+ pool: {
129
+ ...poolConfig,
130
+ acquireTimeoutMillis: 6e5
131
+ }
132
+ };
133
+ const engine = knex(dbConfig);
134
+ return new PostgresEngine(PostgresEngine._createKey, engine);
135
+ }
136
+ /**
137
+ * Create a table for saving of vectors to be used with PostgresVectorStore.
138
+ *
139
+ * @param tableName Postgres database table name. Parameter is not escaped. Do not use with end user input.
140
+ * @param vectorSize Vector size for the embedding model to be used.
141
+ * @param schemaName The schema name to store Postgres database table. Default: "public". Parameter is not escaped. Do not use with end user input.
142
+ * @param contentColumn Name of the column to store document content. Default: "content".
143
+ * @param embeddingColumn Name of the column to store vector embeddings. Default: "embedding".
144
+ * @param embeddingColumnType Type of the embedding column ("vector" | "halfvec" | "bit" | "sparsevec"). Default: "vector". More info on HNSW-supported types: https://github.com/pgvector/pgvector#hnsw
145
+ * @param metadataColumns Optional - A list of Columns to create for custom metadata. Default: [].
146
+ * @param metadataJsonColumn Optional - The column to store extra metadata in JSON format. Default: "langchain_metadata".
147
+ * @param idColumn Optional - Column to store ids. Default: "langchain_id" column name with data type UUID.
148
+ * @param overwriteExisting Whether to drop existing table. Default: False.
149
+ * @param storeMetadata Whether to store metadata in the table. Default: True.
150
+ */
151
+ async initVectorstoreTable(tableName, vectorSize, { schemaName = "public", contentColumn = "content", embeddingColumn = "embedding", embeddingColumnType = "vector", metadataColumns = [], metadataJsonColumn = "langchain_metadata", idColumn = "langchain_id", overwriteExisting = false, storeMetadata = true } = {}) {
152
+ await this.pool.raw("CREATE EXTENSION IF NOT EXISTS vector");
153
+ if (overwriteExisting) await this.pool.schema.withSchema(schemaName).dropTableIfExists(tableName);
154
+ const idDataType = typeof idColumn === "string" ? "UUID" : idColumn.dataType;
155
+ const idColumnName = typeof idColumn === "string" ? idColumn : idColumn.name;
156
+ let query = `CREATE TABLE ${schemaName}.${tableName}(
197
157
  ${idColumnName} ${idDataType} PRIMARY KEY,
198
158
  ${contentColumn} TEXT NOT NULL,
199
- ${embeddingColumn} vector(${vectorSize}) NOT NULL`;
200
- for (const column of metadataColumns) {
201
- const nullable = !column.nullable ? "NOT NULL" : "";
202
- query += `,\n ${column.name} ${column.dataType} ${nullable}`;
203
- }
204
- if (storeMetadata) {
205
- query += `,\n${metadataJsonColumn} JSON`;
206
- }
207
- query += `\n);`;
208
- await this.pool.raw(query);
209
- }
210
- /**
211
- * Create a Cloud SQL table to store chat history.
212
- *
213
- * @param tableName Table name to store chat history
214
- * @param schemaName Schema name to store chat history table
215
- */
216
- async initChatHistoryTable(tableName, schemaName = "public") {
217
- await this.pool.raw(`CREATE TABLE IF NOT EXISTS ${schemaName}.${tableName}(
159
+ ${embeddingColumn} ${embeddingColumnType}(${vectorSize}) NOT NULL`;
160
+ for (const column of metadataColumns) {
161
+ const nullable = !column.nullable ? "NOT NULL" : "";
162
+ query += `,\n ${column.name} ${column.dataType} ${nullable}`;
163
+ }
164
+ if (storeMetadata) query += `,\n${metadataJsonColumn} JSON`;
165
+ query += `\n);`;
166
+ await this.pool.raw(query);
167
+ }
168
+ /**
169
+ * Create a Cloud SQL table to store chat history.
170
+ *
171
+ * @param tableName Table name to store chat history
172
+ * @param schemaName Schema name to store chat history table
173
+ */
174
+ async initChatHistoryTable(tableName, schemaName = "public") {
175
+ await this.pool.raw(`CREATE TABLE IF NOT EXISTS ${schemaName}.${tableName}(
218
176
  id SERIAL PRIMARY KEY,
219
177
  session_id TEXT NOT NULL,
220
178
  data JSONB NOT NULL,
221
179
  type TEXT NOT NULL);`);
222
- }
223
- /**
224
- * Dispose of connection pool
225
- */
226
- async closeConnection() {
227
- await this.pool.destroy();
228
- if (PostgresEngine.connector !== undefined) {
229
- PostgresEngine.connector.close();
230
- }
231
- }
232
- // Just to test the connection to the database
233
- testConnection() {
234
- const now = this.pool.raw("SELECT NOW() as currentTimestamp");
235
- return now;
236
- }
237
- }
238
- Object.defineProperty(PostgresEngine, "_createKey", {
239
- enumerable: true,
240
- configurable: true,
241
- writable: true,
242
- value: Symbol("key")
243
- });
244
- export default PostgresEngine;
180
+ }
181
+ /**
182
+ * Dispose of connection pool
183
+ */
184
+ async closeConnection() {
185
+ await this.pool.destroy();
186
+ if (PostgresEngine.connector !== void 0) PostgresEngine.connector.close();
187
+ }
188
+ testConnection() {
189
+ const now = this.pool.raw("SELECT NOW() as currentTimestamp");
190
+ return now;
191
+ }
192
+ };
193
+
194
+ //#endregion
195
+ export { Column, PostgresEngine };
196
+ //# sourceMappingURL=engine.js.map