@ragestudio/scylla-odm 0.1.0 → 0.2.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.
@@ -0,0 +1,113 @@
1
+ import * as _$cassandra_driver0 from "cassandra-driver";
2
+ import { Client, mapping } from "cassandra-driver";
3
+ import { mapping as mapping$1 } from "cassandra-driver/lib/mapping/index.js";
4
+
5
+ //#region src/schema/index.d.ts
6
+ declare class Schema<T> {
7
+ readonly table_name: string;
8
+ readonly clustering_order: any;
9
+ readonly keys: TableKeys;
10
+ readonly fields: T;
11
+ constructor(params: any, fields: T);
12
+ }
13
+ //#endregion
14
+ //#region src/operations/tableExists.d.ts
15
+ declare function export_default(this: Model): Promise<boolean>;
16
+ //#endregion
17
+ //#region src/operations/sync.d.ts
18
+ declare function syncOP(this: Model): Promise<void>;
19
+ //#endregion
20
+ //#region src/model/index.d.ts
21
+ declare class Model<TDoc = any> {
22
+ name: string;
23
+ schema: Schema<any>;
24
+ driver: ScyllaClient;
25
+ mapper: mapping$1.ModelMapper;
26
+ constructor(name: string, schema: Schema<any>);
27
+ create: (data: Partial<TDoc>) => DocumentResult<TDoc>;
28
+ find: {
29
+ (query: Query<TDoc>, options: QueryOptions & {
30
+ raw: true;
31
+ }): Promise<TDoc[]>;
32
+ (query?: Query<TDoc>, options?: QueryOptions): Promise<DocumentResult<TDoc>[]>;
33
+ };
34
+ findOne: {
35
+ (query: Query<TDoc>, options: QueryOptions & {
36
+ raw: true;
37
+ }): Promise<TDoc>;
38
+ (query?: Query<TDoc>, options?: QueryOptions): Promise<DocumentResult<TDoc>>;
39
+ };
40
+ update: (query: Query<TDoc>) => Promise<DocumentResult<TDoc>>;
41
+ delete: (query: Query<TDoc>) => Promise<mapping$1.Result>;
42
+ countAll: () => Promise<number>;
43
+ _sync: typeof syncOP;
44
+ _tableExists: typeof export_default;
45
+ _wrap(row: any): DocumentResult<TDoc> | null;
46
+ _connect(driver: ScyllaClient): void;
47
+ }
48
+ //#endregion
49
+ //#region src/result/index.d.ts
50
+ declare class Result<TDoc = any> {
51
+ constructor(data: TDoc, model: Model<TDoc>);
52
+ _model: Model<TDoc>;
53
+ save(): Promise<DocumentResult<TDoc>>;
54
+ delete(): Promise<_$cassandra_driver0.mapping.Result<any>>;
55
+ toRaw(): TDoc;
56
+ isValid(): boolean;
57
+ getChangedFields(original: Partial<TDoc>): (keyof TDoc)[];
58
+ }
59
+ //#endregion
60
+ //#region src/types.d.ts
61
+ type ClientConfig = {
62
+ modelsPath?: string;
63
+ contactPoints?: string[];
64
+ localDataCenter?: string;
65
+ keyspace?: string;
66
+ port?: number;
67
+ maxRetries?: number;
68
+ retryDelay?: number;
69
+ pooling?: {
70
+ coreConnectionsPerHost?: Record<string, number>;
71
+ maxRequestsPerConnection?: number;
72
+ };
73
+ };
74
+ type QueryOperators<TValue> = {
75
+ $eq?: TValue;
76
+ $ne?: TValue;
77
+ $in?: TValue[];
78
+ $gt?: TValue;
79
+ $gte?: TValue;
80
+ $lt?: TValue;
81
+ $lte?: TValue;
82
+ };
83
+ type TableKeys = (string | TableKeys)[];
84
+ type DocumentResult<TDoc> = Result<TDoc> & TDoc;
85
+ type QueryOptions = {
86
+ raw?: boolean;
87
+ };
88
+ type OrderBy<TDoc> = { [K in keyof TDoc]?: "asc" | "desc" };
89
+ type Query<TDoc> = { [K in keyof TDoc]?: TDoc[K] | QueryOperators<TDoc[K]> } & {
90
+ $and?: Query<TDoc>[];
91
+ $limit?: number;
92
+ $orderby?: OrderBy<TDoc>;
93
+ };
94
+ //#endregion
95
+ //#region src/index.d.ts
96
+ declare class ScyllaClient {
97
+ constructor(config?: ClientConfig);
98
+ config: ClientConfig;
99
+ client: Client;
100
+ mapper: mapping.Mapper;
101
+ models: Map<string, Model<any>>;
102
+ initialize(options?: {
103
+ sync?: boolean;
104
+ }): Promise<void>;
105
+ private connectWithRetry;
106
+ private delay;
107
+ shutdown(): Promise<void>;
108
+ executeWithRetry<T>(operation: () => Promise<T>, operationName?: string): Promise<T>;
109
+ private isRetryableError;
110
+ }
111
+ //#endregion
112
+ export { ScyllaClient as default };
113
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,519 @@
1
+ import path from "node:path";
2
+ import Cassandra from "cassandra-driver";
3
+ import fs from "node:fs";
4
+ //#region src/utils/loadSchemas.ts
5
+ var loadSchemas_default = async (fromPath) => {
6
+ if (typeof fromPath !== "string") return [];
7
+ if (!fs.existsSync(fromPath)) {
8
+ console.warn(`Cannot load models from [${fromPath}] case this path does not exist`);
9
+ return [];
10
+ }
11
+ let schemas = [];
12
+ let files = await fs.promises.readdir(fromPath);
13
+ files = files.filter((file) => file.endsWith(".js") || file.endsWith(".ts"));
14
+ for await (const file of files) {
15
+ const name = file.replace(".js", "");
16
+ const file_path = path.join(fromPath, file);
17
+ try {
18
+ let mod = await import(file_path);
19
+ mod = mod.default;
20
+ schemas.push(mod);
21
+ } catch (error) {
22
+ console.error(`Failed to load schema [${name}]:`, error);
23
+ continue;
24
+ }
25
+ }
26
+ return schemas;
27
+ };
28
+ //#endregion
29
+ //#region src/utils/buildMapper.ts
30
+ var buildMapper_default = (map) => {
31
+ return map.reduce((obj, { name, schema }) => {
32
+ return {
33
+ ...obj,
34
+ [name]: { tables: [schema.table_name] }
35
+ };
36
+ }, {});
37
+ };
38
+ //#endregion
39
+ //#region src/utils/queryParser.ts
40
+ const { q } = Cassandra.mapping;
41
+ const MAX_QUERY_DEPTH = 3;
42
+ const MAX_IN_ELEMENTS = 1e3;
43
+ const VALID_OPERATORS = new Set([
44
+ "$eq",
45
+ "$ne",
46
+ "$gt",
47
+ "$gte",
48
+ "$lt",
49
+ "$lte",
50
+ "$in"
51
+ ]);
52
+ function requireNotNull(value, operator) {
53
+ if (value === null || value === void 0) throw new Error(`${operator} operator cannot compare with null or undefined`);
54
+ }
55
+ function buildOperator(operator, opValue) {
56
+ if (!VALID_OPERATORS.has(operator)) throw new Error(`Invalid operator: ${operator}`);
57
+ switch (operator) {
58
+ case "$eq": return opValue;
59
+ case "$ne":
60
+ requireNotNull(opValue, "$ne");
61
+ return q.notEq(opValue);
62
+ case "$in":
63
+ if (!Array.isArray(opValue)) throw new Error("$in operator requires an array");
64
+ if (opValue.length > MAX_IN_ELEMENTS) throw new Error(`$in operator exceeds maximum of ${MAX_IN_ELEMENTS} elements`);
65
+ for (let i = 0; i < opValue.length; i++) if (opValue[i] === null || opValue[i] === void 0) throw new Error(`$in array element at index ${i} cannot be null or undefined`);
66
+ return q.in_(opValue);
67
+ case "$gt":
68
+ requireNotNull(opValue, "$gt");
69
+ return q.gt(opValue);
70
+ case "$gte":
71
+ requireNotNull(opValue, "$gte");
72
+ return q.gte(opValue);
73
+ case "$lt":
74
+ requireNotNull(opValue, "$lt");
75
+ return q.lt(opValue);
76
+ case "$lte":
77
+ requireNotNull(opValue, "$lte");
78
+ return q.lte(opValue);
79
+ }
80
+ }
81
+ function queryParser(model, query, depth = 0) {
82
+ if (depth > MAX_QUERY_DEPTH) throw new Error(`Query depth exceeds maximum of ${MAX_QUERY_DEPTH}`);
83
+ if (!query || typeof query !== "object") return query;
84
+ const parsedQuery = {};
85
+ const fields = model.schema.fields;
86
+ for (const field of Object.keys(query)) {
87
+ const value = query[field];
88
+ if (field === "$and") {
89
+ handleAnd(model, value, parsedQuery, depth);
90
+ continue;
91
+ }
92
+ if (field === "$or") throw new Error("ScyllaDB does not support OR queries across different columns. Use $in for a single column.");
93
+ if (!isValidFieldName(fields, field)) throw new Error(`Invalid field name: [${field}] or it does not exist in schema`);
94
+ parsedQuery[field] = parseField(value);
95
+ }
96
+ return parsedQuery;
97
+ }
98
+ function handleAnd(model, conditions, parsedQuery, depth) {
99
+ if (!Array.isArray(conditions)) throw new Error("$and operator requires an array");
100
+ if (conditions.length > 10) throw new Error("$and operator exceeds maximum of 10 conditions");
101
+ for (let i = 0; i < conditions.length; i++) {
102
+ const condition = conditions[i];
103
+ if (!condition || typeof condition !== "object") throw new Error(`$and condition at index ${i} must be an object`);
104
+ const parsed = queryParser(model, condition, depth + 1);
105
+ for (const key of Object.keys(parsed)) if (key in parsedQuery) throw new Error(`$and conflict: field "${key}" appears in multiple conditions`);
106
+ Object.assign(parsedQuery, parsed);
107
+ }
108
+ }
109
+ function parseField(value) {
110
+ if (value === null || typeof value !== "object" || Array.isArray(value) || value instanceof Date) {
111
+ if (Array.isArray(value)) throw new Error("Array values require explicit operator (e.g., $in)");
112
+ return value;
113
+ }
114
+ const compiledOps = Object.keys(value).map((op) => buildOperator(op, value[op]));
115
+ return compiledOps.length === 1 ? compiledOps[0] : q.and(...compiledOps);
116
+ }
117
+ function isValidFieldName(fields, fieldName) {
118
+ for (const pattern of [
119
+ /^[0-9]/,
120
+ /[^a-zA-Z0-9_]/,
121
+ /^(select|insert|update|delete|drop|create|alter|truncate)$/i
122
+ ]) if (pattern.test(fieldName)) return false;
123
+ return fieldName in fields;
124
+ }
125
+ //#endregion
126
+ //#region src/utils/typeChecker.ts
127
+ const { types } = Cassandra;
128
+ const stringTypes = new Set([
129
+ "ascii",
130
+ "text",
131
+ "varchar",
132
+ "inet"
133
+ ]);
134
+ const intTypes = new Set([
135
+ "int",
136
+ "smallint",
137
+ "tinyint"
138
+ ]);
139
+ const floatTypes = new Set(["double", "float"]);
140
+ const longTypes = new Set(["bigint", "counter"]);
141
+ function isValidValue(value, expectedType) {
142
+ if (value === null || value === void 0) return true;
143
+ if (stringTypes.has(expectedType)) return typeof value === "string";
144
+ if (intTypes.has(expectedType)) return Number.isInteger(value);
145
+ if (floatTypes.has(expectedType)) return typeof value === "number";
146
+ if (longTypes.has(expectedType)) return typeof value === "bigint" || typeof value === "number" || value instanceof types.Long;
147
+ switch (expectedType) {
148
+ case "boolean": return typeof value === "boolean";
149
+ case "decimal": return typeof value === "number" || typeof value === "string" || value instanceof types.BigDecimal;
150
+ case "varint": return typeof value === "bigint" || typeof value === "number" || value instanceof types.Integer;
151
+ case "timestamp": return value instanceof Date || typeof value === "number" || typeof value === "string";
152
+ case "date": return typeof value === "string" || value instanceof types.LocalDate;
153
+ case "time": return typeof value === "string" || value instanceof types.LocalTime;
154
+ case "uuid": return typeof value === "string" || value instanceof types.Uuid;
155
+ case "timeuuid": return typeof value === "string" || value instanceof types.TimeUuid;
156
+ case "blob": return Buffer.isBuffer(value) || value instanceof Uint8Array;
157
+ }
158
+ if (expectedType.startsWith("list<") || expectedType.startsWith("set<")) return Array.isArray(value) || value instanceof Set;
159
+ if (expectedType.startsWith("map<")) return typeof value === "object" && !Array.isArray(value) && value !== null;
160
+ return false;
161
+ }
162
+ function typeChecker(model, data) {
163
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new TypeError(`[${model.name}] Validation error: Data payload must be an object`);
164
+ const fields = model.schema.fields;
165
+ for (const [key, value] of Object.entries(data)) {
166
+ if (!isValidFieldName(fields, key)) throw new Error(`[${model.name}] Validation error: Field '${key}' does not exist in schema`);
167
+ const expectedType = (fields[key].type || "text").toLowerCase();
168
+ if (!isValidValue(value, expectedType)) {
169
+ const receivedType = Array.isArray(value) ? "array" : typeof value;
170
+ throw new TypeError(`[${model.name}] Validation error: Invalid type for field '${key}'. Expected[${expectedType}], but received [${receivedType}]`);
171
+ }
172
+ }
173
+ return true;
174
+ }
175
+ //#endregion
176
+ //#region src/result/index.ts
177
+ var Result = class {
178
+ constructor(data, model) {
179
+ if (data == null) throw new Error("Cannot create Result with null or undefined data");
180
+ if (typeof data !== "object" || Array.isArray(data)) throw new Error("Result data must be an object");
181
+ Object.assign(this, data);
182
+ Object.defineProperty(this, "_model", {
183
+ value: model,
184
+ enumerable: false,
185
+ writable: false,
186
+ configurable: false
187
+ });
188
+ }
189
+ _model;
190
+ async save() {
191
+ try {
192
+ const data = this.toRaw();
193
+ typeChecker(this._model, data);
194
+ return await this._model.update(data);
195
+ } catch (error) {
196
+ throw new Error(`Failed to save result: ${error.message}`);
197
+ }
198
+ }
199
+ async delete() {
200
+ try {
201
+ return await this._model.delete(this.toRaw());
202
+ } catch (error) {
203
+ throw new Error(`Failed to delete result: ${error.message}`);
204
+ }
205
+ }
206
+ toRaw() {
207
+ const raw = {};
208
+ for (const key in this) {
209
+ if (key === "_model") continue;
210
+ if (this.propertyIsEnumerable(key)) {
211
+ const value = this[key];
212
+ try {
213
+ JSON.stringify(value);
214
+ raw[key] = value;
215
+ } catch (error) {
216
+ raw[key] = String(value);
217
+ }
218
+ }
219
+ }
220
+ return raw;
221
+ }
222
+ isValid() {
223
+ try {
224
+ typeChecker(this._model, this.toRaw());
225
+ return true;
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+ getChangedFields(original) {
231
+ const current = this.toRaw();
232
+ const changed = [];
233
+ for (const key in current) if (!(key in original) || current[key] !== original[key]) changed.push(key);
234
+ return changed;
235
+ }
236
+ };
237
+ //#endregion
238
+ //#region src/utils/fillDefaults.ts
239
+ function fillDefaults(schema, data) {
240
+ const defaults = schema.options?.defaults;
241
+ if (!defaults || Object.keys(defaults).length === 0) return data;
242
+ let needsDefaults = false;
243
+ for (const key in defaults) if (data[key] == null) {
244
+ needsDefaults = true;
245
+ break;
246
+ }
247
+ if (!needsDefaults) return data;
248
+ const result = Object.assign({}, data);
249
+ for (const key in defaults) if (result[key] == null) result[key] = defaults[key];
250
+ return result;
251
+ }
252
+ //#endregion
253
+ //#region src/operations/findOne.ts
254
+ function findOne_default(query, options) {
255
+ query = queryParser(this, query);
256
+ const operation = async () => {
257
+ let result = await this.mapper.get(query);
258
+ if (!result) return null;
259
+ result = this._wrap(result);
260
+ if (options?.raw === true) return result.toRaw();
261
+ return result;
262
+ };
263
+ return this.driver.executeWithRetry(operation, `findOne on ${this.name}`);
264
+ }
265
+ //#endregion
266
+ //#region src/operations/find.ts
267
+ async function findOP(query = {}, options) {
268
+ const { $limit, $orderby, ...rest } = query;
269
+ let parsedQuery = queryParser(this, rest);
270
+ const docInfo = {};
271
+ if ($limit !== void 0) {
272
+ if (typeof $limit !== "number" || $limit <= 0) throw new TypeError(`{$limit} operator must be a number greater than 0`);
273
+ docInfo.limit = $limit;
274
+ }
275
+ if ($orderby !== void 0) docInfo.orderBy = $orderby;
276
+ const operation = async () => {
277
+ const rows = (await this.mapper.find(parsedQuery, docInfo)).toArray();
278
+ if (options?.raw === true) return rows;
279
+ return rows.map((row) => this._wrap(row));
280
+ };
281
+ return this.driver.executeWithRetry(operation, `find on ${this.name}`);
282
+ }
283
+ //#endregion
284
+ //#region src/operations/update.ts
285
+ async function update_default(query) {
286
+ query = fillDefaults(this.schema, query);
287
+ typeChecker(this, query);
288
+ if (typeof query.__v !== "undefined") if (Number.isNaN(query.__v)) query.__v = 0;
289
+ else query.__v = query.__v + 1;
290
+ const operation = async () => {
291
+ await this.mapper.update(query);
292
+ return this._wrap(query);
293
+ };
294
+ return this.driver.executeWithRetry(operation, `update on ${this.name}`);
295
+ }
296
+ //#endregion
297
+ //#region src/operations/delete.ts
298
+ async function delete_default(query) {
299
+ const operation = async () => {
300
+ return await this.mapper.remove(query);
301
+ };
302
+ return this.driver.executeWithRetry(operation, `delete on ${this.name}`);
303
+ }
304
+ //#endregion
305
+ //#region src/operations/countAll.ts
306
+ async function countAll_default(timeoutMs = 6e4) {
307
+ const cql = `SELECT COUNT(1) FROM ${this.driver.config.keyspace}.${this.schema.table_name}`;
308
+ const queryOptions = {
309
+ prepare: true,
310
+ readTimeout: timeoutMs
311
+ };
312
+ const operation = async () => {
313
+ return (await this.driver.client.execute(cql, [], queryOptions)).rows[0].count.toNumber();
314
+ };
315
+ return this.driver.executeWithRetry(operation, `countAll on ${this.name}`);
316
+ }
317
+ //#endregion
318
+ //#region src/operations/tableExists.ts
319
+ async function tableExists_default() {
320
+ const cql = `
321
+ SELECT table_name
322
+ FROM system_schema.tables
323
+ WHERE keyspace_name = ?
324
+ AND table_name = ?
325
+ `;
326
+ try {
327
+ return (await this.driver.client.execute(cql, [this.driver.config.keyspace, this.schema.table_name], { prepare: true })).rows.length > 0;
328
+ } catch (error) {
329
+ console.error(`Failed to check if table "${this.schema.table_name}" exists:`, error);
330
+ return false;
331
+ }
332
+ }
333
+ //#endregion
334
+ //#region src/cql_gen/create_table.ts
335
+ function create_table_default(model) {
336
+ const desc = model.schema;
337
+ const tableName = desc.table_name;
338
+ const keyspace = model.driver.config.keyspace;
339
+ const fields = desc.fields;
340
+ const key = desc.keys;
341
+ const clusteringOrder = desc.clustering_order;
342
+ let columnsDef = "";
343
+ for (const fieldName in fields) {
344
+ const field = fields[fieldName];
345
+ const typeStr = typeof field === "string" ? field : field?.type;
346
+ if (!typeStr) throw new Error(`Invalid field type for "${fieldName}" in model "${tableName}"`);
347
+ columnsDef += `"${fieldName}" ${typeStr.toUpperCase()}, `;
348
+ }
349
+ let pkDef = "";
350
+ if (typeof key === "string") pkDef = `"${key}"`;
351
+ else if (Array.isArray(key) && key.length > 0) {
352
+ const first = key[0];
353
+ if (Array.isArray(first)) pkDef = `(${first.map((k) => `"${k}"`).join(", ")})`;
354
+ else pkDef = `"${first}"`;
355
+ for (let i = 1; i < key.length; i++) pkDef += `, "${key[i]}"`;
356
+ } else throw new Error(`Missing or invalid primary key in model "${tableName}"`);
357
+ let clusterClause = "";
358
+ if (clusteringOrder) {
359
+ let orderDef = "";
360
+ for (const col in clusteringOrder) {
361
+ if (orderDef !== "") orderDef += ", ";
362
+ orderDef += `"${col}" ${clusteringOrder[col].toUpperCase()}`;
363
+ }
364
+ if (orderDef !== "") clusterClause = ` WITH CLUSTERING ORDER BY (${orderDef})`;
365
+ }
366
+ return `CREATE TABLE IF NOT EXISTS ${keyspace}.${tableName} (${columnsDef}PRIMARY KEY (${pkDef}))${clusterClause}`;
367
+ }
368
+ //#endregion
369
+ //#region src/operations/sync.ts
370
+ async function syncOP() {
371
+ if (await this._tableExists()) return;
372
+ try {
373
+ await this.driver.client.execute(create_table_default(this));
374
+ console.log(`Table "${this.schema.table_name}" created successfully`);
375
+ } catch (error) {
376
+ console.error(`Failed to create table "${this.schema.table_name}":`, error);
377
+ throw error;
378
+ }
379
+ }
380
+ //#endregion
381
+ //#region src/model/index.ts
382
+ var Model = class {
383
+ name;
384
+ schema;
385
+ driver;
386
+ mapper;
387
+ constructor(name, schema) {
388
+ this.name = name;
389
+ this.schema = schema;
390
+ if (!Array.isArray(this.schema.keys)) throw new Error(`[${this.name}] model has missing "keys" array`);
391
+ if (!this.schema.table_name) throw new Error(`[${this.name}] model has missing "table_name"`);
392
+ if (!this.schema.fields || typeof this.schema.fields !== "object") throw new Error(`[${this.name}] model has missing or invalid "fields"`);
393
+ }
394
+ create = (data) => this._wrap(data);
395
+ find = findOP.bind(this);
396
+ findOne = findOne_default.bind(this);
397
+ update = update_default.bind(this);
398
+ delete = delete_default.bind(this);
399
+ countAll = countAll_default.bind(this);
400
+ _sync = syncOP.bind(this);
401
+ _tableExists = tableExists_default.bind(this);
402
+ _wrap(row) {
403
+ if (!row) return null;
404
+ row = fillDefaults(this.schema, row);
405
+ return new Result(row, this);
406
+ }
407
+ _connect(driver) {
408
+ this.driver = driver;
409
+ this.mapper = driver.mapper.forModel(this.name);
410
+ }
411
+ };
412
+ //#endregion
413
+ //#region src/index.ts
414
+ const DEFAULT_MAX_RETRIES = 3;
415
+ const DEFAULT_RETRY_DELAY = 1e3;
416
+ const { SCYLLA_CONTACT_POINTS, SCYLLA_LOCAL_DATA_CENTER, SCYLLA_KEYSPACE } = process.env;
417
+ var ScyllaClient = class {
418
+ constructor(config = {}) {
419
+ this.config = {
420
+ modelsPath: path.resolve(__dirname, "../../db"),
421
+ contactPoints: config.contactPoints ?? SCYLLA_CONTACT_POINTS ? SCYLLA_CONTACT_POINTS.split(",") : ["127.0.0.1"],
422
+ localDataCenter: config.localDataCenter ?? SCYLLA_LOCAL_DATA_CENTER ?? "datacenter1",
423
+ keyspace: config.keyspace ?? SCYLLA_KEYSPACE ?? "default",
424
+ port: 9042,
425
+ maxRetries: DEFAULT_MAX_RETRIES,
426
+ retryDelay: DEFAULT_RETRY_DELAY,
427
+ ...config
428
+ };
429
+ const clientOptions = {
430
+ contactPoints: this.config.contactPoints,
431
+ localDataCenter: this.config.localDataCenter,
432
+ keyspace: this.config.keyspace,
433
+ protocolOptions: { port: this.config.port }
434
+ };
435
+ if (this.config.pooling) clientOptions.pooling = this.config.pooling;
436
+ this.client = new Cassandra.Client(clientOptions);
437
+ }
438
+ config;
439
+ client;
440
+ mapper;
441
+ models = /* @__PURE__ */ new Map();
442
+ async initialize(options = {}) {
443
+ let models;
444
+ try {
445
+ models = await loadSchemas_default(this.config.modelsPath);
446
+ } catch (error) {
447
+ throw new Error(`Failed to load models: ${error.message}`);
448
+ }
449
+ models = models.filter((schema) => schema instanceof Model);
450
+ this.mapper = new Cassandra.mapping.Mapper(this.client, { models: buildMapper_default(models) });
451
+ for (let model of models) {
452
+ model._connect(this);
453
+ this.models.set(model.name, model);
454
+ if (options?.sync === true) await model._sync();
455
+ }
456
+ console.log("Connecting to ScyllaDB");
457
+ await this.connectWithRetry();
458
+ console.log("ScyllaDB Connected");
459
+ }
460
+ async connectWithRetry() {
461
+ let lastError = null;
462
+ for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) try {
463
+ await this.client.connect();
464
+ return;
465
+ } catch (error) {
466
+ lastError = error;
467
+ console.warn(`Connection attempt ${attempt} failed: ${error.message}`);
468
+ if (attempt < this.config.maxRetries) {
469
+ console.log(`Retrying in ${this.config.retryDelay}ms...`);
470
+ await this.delay(this.config.retryDelay);
471
+ }
472
+ }
473
+ throw new Error(`Failed to connect to ScyllaDB after ${this.config.maxRetries} attempts: ${lastError?.message}`);
474
+ }
475
+ delay(ms) {
476
+ return new Promise((resolve) => setTimeout(resolve, ms));
477
+ }
478
+ async shutdown() {
479
+ try {
480
+ await this.client.shutdown();
481
+ console.log("ScyllaDB connection closed");
482
+ } catch (error) {
483
+ console.error("Error shutting down ScyllaDB connection:", error);
484
+ throw error;
485
+ }
486
+ }
487
+ async executeWithRetry(operation, operationName = "operation") {
488
+ let lastError = null;
489
+ for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) try {
490
+ return await operation();
491
+ } catch (error) {
492
+ lastError = error;
493
+ if (this.isRetryableError(error) && attempt < this.config.maxRetries) {
494
+ console.warn(`Operation ${operationName} attempt ${attempt} failed: ${error.message}`);
495
+ console.log(`Retrying in ${this.config.retryDelay}ms...`);
496
+ await this.delay(this.config.retryDelay);
497
+ continue;
498
+ }
499
+ throw error;
500
+ }
501
+ throw new Error(`Operation ${operationName} failed after ${this.config.maxRetries} attempts: ${lastError?.message}`);
502
+ }
503
+ isRetryableError(error) {
504
+ const retryableMessages = [
505
+ "timeout",
506
+ "connection",
507
+ "network",
508
+ "unavailable",
509
+ "overloaded",
510
+ "no hosts available"
511
+ ];
512
+ const errorMessage = error.message?.toLowerCase() || "";
513
+ return retryableMessages.some((msg) => errorMessage.includes(msg));
514
+ }
515
+ };
516
+ //#endregion
517
+ export { ScyllaClient as default };
518
+
519
+ //# sourceMappingURL=index.mjs.map