@ragestudio/scylla-odm 0.1.0 → 0.3.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.d.mts +113 -0
- package/dist/index.mjs +519 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +22 -2
- package/src/cql_gen/create_table.ts +0 -66
- package/src/index.ts +0 -186
- package/src/model/index.ts +0 -93
- package/src/operations/countAll.ts +0 -18
- package/src/operations/delete.ts +0 -9
- package/src/operations/find.ts +0 -42
- package/src/operations/findOne.ts +0 -25
- package/src/operations/sync.ts +0 -22
- package/src/operations/tableExists.ts +0 -29
- package/src/operations/update.ts +0 -24
- package/src/result/index.ts +0 -90
- package/src/schema/index.ts +0 -16
- package/src/types.ts +0 -89
- package/src/utils/buildMapper.js +0 -10
- package/src/utils/fillDefaults.ts +0 -30
- package/src/utils/loadSchemas.ts +0 -39
- package/src/utils/queryParser.ts +0 -192
- package/src/utils/typeChecker.ts +0 -100
- package/tsconfig.json +0 -19
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["cassandra","cassandra","generateCreateTableCQL","findOneOP","updateOP","deleteOP","countAllOP","tableExistsOP","loadSchemas","buildMapper"],"sources":["../src/utils/loadSchemas.ts","../src/utils/buildMapper.ts","../src/utils/queryParser.ts","../src/utils/typeChecker.ts","../src/result/index.ts","../src/utils/fillDefaults.ts","../src/operations/findOne.ts","../src/operations/find.ts","../src/operations/update.ts","../src/operations/delete.ts","../src/operations/countAll.ts","../src/operations/tableExists.ts","../src/cql_gen/create_table.ts","../src/operations/sync.ts","../src/model/index.ts","../src/index.ts"],"sourcesContent":["import fs from \"node:fs\"\nimport path from \"node:path\"\n\nexport default async (fromPath: string): Promise<any[]> => {\n\tif (typeof fromPath !== \"string\") {\n\t\treturn []\n\t}\n\n\tif (!fs.existsSync(fromPath)) {\n\t\tconsole.warn(\n\t\t\t`Cannot load models from [${fromPath}] case this path does not exist`,\n\t\t)\n\t\treturn []\n\t}\n\n\tlet schemas = []\n\n\tlet files = await fs.promises.readdir(fromPath)\n\n\tfiles = files.filter((file) => file.endsWith(\".js\") || file.endsWith(\".ts\"))\n\n\tfor await (const file of files) {\n\t\tconst name = file.replace(\".js\", \"\")\n\t\tconst file_path = path.join(fromPath, file)\n\n\t\ttry {\n\t\t\tlet mod = await import(file_path)\n\n\t\t\tmod = mod.default\n\n\t\t\tschemas.push(mod)\n\t\t} catch (error) {\n\t\t\tconsole.error(`Failed to load schema [${name}]:`, error)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn schemas\n}\n","export default (map) => {\n\treturn map.reduce((obj, { name, schema }) => {\n\t\treturn {\n\t\t\t...obj,\n\t\t\t[name]: {\n\t\t\t\ttables: [schema.table_name],\n\t\t\t},\n\t\t}\n\t}, {})\n}\n","import type { Model } from \"../model\"\n\n// @ts-ignore\nimport cassandra from \"cassandra-driver\"\nconst { q } = cassandra.mapping\n\nconst MAX_QUERY_DEPTH = 3\nconst MAX_IN_ELEMENTS = 1000\n\nconst VALID_OPERATORS = new Set([\n\t\"$eq\",\n\t\"$ne\",\n\t\"$gt\",\n\t\"$gte\",\n\t\"$lt\",\n\t\"$lte\",\n\t\"$in\",\n])\n\nfunction requireNotNull(value: any, operator: string): void {\n\tif (value === null || value === undefined) {\n\t\tthrow new Error(\n\t\t\t`${operator} operator cannot compare with null or undefined`,\n\t\t)\n\t}\n}\n\nfunction buildOperator(operator: string, opValue: any): any {\n\tif (!VALID_OPERATORS.has(operator)) {\n\t\tthrow new Error(`Invalid operator: ${operator}`)\n\t}\n\n\tswitch (operator) {\n\t\tcase \"$eq\":\n\t\t\treturn opValue\n\n\t\tcase \"$ne\":\n\t\t\trequireNotNull(opValue, \"$ne\")\n\t\t\treturn q.notEq(opValue)\n\n\t\tcase \"$in\":\n\t\t\tif (!Array.isArray(opValue)) {\n\t\t\t\tthrow new Error(\"$in operator requires an array\")\n\t\t\t}\n\t\t\tif (opValue.length > MAX_IN_ELEMENTS) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`$in operator exceeds maximum of ${MAX_IN_ELEMENTS} elements`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tfor (let i = 0; i < opValue.length; i++) {\n\t\t\t\tif (opValue[i] === null || opValue[i] === undefined) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`$in array element at index ${i} cannot be null or undefined`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn q.in_(opValue)\n\n\t\tcase \"$gt\":\n\t\t\trequireNotNull(opValue, \"$gt\")\n\t\t\treturn q.gt(opValue)\n\n\t\tcase \"$gte\":\n\t\t\trequireNotNull(opValue, \"$gte\")\n\t\t\treturn q.gte(opValue)\n\n\t\tcase \"$lt\":\n\t\t\trequireNotNull(opValue, \"$lt\")\n\t\t\treturn q.lt(opValue)\n\n\t\tcase \"$lte\":\n\t\t\trequireNotNull(opValue, \"$lte\")\n\t\t\treturn q.lte(opValue)\n\t}\n}\n\nexport default function queryParser(\n\tmodel: Model<any>,\n\tquery: any,\n\tdepth: number = 0,\n) {\n\tif (depth > MAX_QUERY_DEPTH) {\n\t\tthrow new Error(`Query depth exceeds maximum of ${MAX_QUERY_DEPTH}`)\n\t}\n\n\tif (!query || typeof query !== \"object\") {\n\t\treturn query\n\t}\n\n\tconst parsedQuery: Record<string, any> = {}\n\tconst fields = model.schema.fields\n\n\tfor (const field of Object.keys(query)) {\n\t\tconst value = query[field]\n\n\t\tif (field === \"$and\") {\n\t\t\thandleAnd(model, value, parsedQuery, depth)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (field === \"$or\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"ScyllaDB does not support OR queries across different columns. Use $in for a single column.\",\n\t\t\t)\n\t\t}\n\n\t\tif (!isValidFieldName(fields, field)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid field name: [${field}] or it does not exist in schema`,\n\t\t\t)\n\t\t}\n\n\t\tparsedQuery[field] = parseField(value)\n\t}\n\n\treturn parsedQuery\n}\n\nfunction handleAnd(\n\tmodel: Model<any>,\n\tconditions: any,\n\tparsedQuery: Record<string, any>,\n\tdepth: number,\n) {\n\tif (!Array.isArray(conditions)) {\n\t\tthrow new Error(\"$and operator requires an array\")\n\t}\n\tif (conditions.length > 10) {\n\t\tthrow new Error(\"$and operator exceeds maximum of 10 conditions\")\n\t}\n\n\tfor (let i = 0; i < conditions.length; i++) {\n\t\tconst condition = conditions[i]\n\t\tif (!condition || typeof condition !== \"object\") {\n\t\t\tthrow new Error(`$and condition at index ${i} must be an object`)\n\t\t}\n\n\t\tconst parsed = queryParser(model, condition, depth + 1)\n\t\tfor (const key of Object.keys(parsed)) {\n\t\t\tif (key in parsedQuery) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`$and conflict: field \"${key}\" appears in multiple conditions`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tObject.assign(parsedQuery, parsed)\n\t}\n}\n\nfunction parseField(value: any): any {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value !== \"object\" ||\n\t\tArray.isArray(value) ||\n\t\tvalue instanceof Date\n\t) {\n\t\tif (Array.isArray(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Array values require explicit operator (e.g., $in)\",\n\t\t\t)\n\t\t}\n\t\treturn value\n\t}\n\n\tconst operators = Object.keys(value)\n\tconst compiledOps = operators.map((op) => buildOperator(op, value[op]))\n\n\treturn compiledOps.length === 1\n\t\t? compiledOps[0]\n\t\t: (q.and as any)(...compiledOps)\n}\n\nexport function isValidFieldName(\n\tfields: Record<string, any>,\n\tfieldName: string,\n): boolean {\n\tconst invalidPatterns = [\n\t\t/^[0-9]/,\n\t\t/[^a-zA-Z0-9_]/,\n\t\t/^(select|insert|update|delete|drop|create|alter|truncate)$/i,\n\t]\n\n\tfor (const pattern of invalidPatterns) {\n\t\tif (pattern.test(fieldName)) return false\n\t}\n\n\treturn fieldName in fields\n}\n\nexport function isValidOperator(operator: string): boolean {\n\treturn VALID_OPERATORS.has(operator)\n}\n","// @ts-ignore\nimport cassandra from \"cassandra-driver\"\nconst { types } = cassandra\nimport type { Model } from \"../model\"\nimport { isValidFieldName } from \"./queryParser\"\n\nconst stringTypes = new Set([\"ascii\", \"text\", \"varchar\", \"inet\"])\nconst intTypes = new Set([\"int\", \"smallint\", \"tinyint\"])\nconst floatTypes = new Set([\"double\", \"float\"])\nconst longTypes = new Set([\"bigint\", \"counter\"])\n\nfunction isValidValue(value: any, expectedType: string): boolean {\n\tif (value === null || value === undefined) return true\n\n\tif (stringTypes.has(expectedType)) return typeof value === \"string\"\n\tif (intTypes.has(expectedType)) return Number.isInteger(value)\n\tif (floatTypes.has(expectedType)) return typeof value === \"number\"\n\tif (longTypes.has(expectedType)) {\n\t\treturn (\n\t\t\ttypeof value === \"bigint\" ||\n\t\t\ttypeof value === \"number\" ||\n\t\t\tvalue instanceof types.Long\n\t\t)\n\t}\n\n\tswitch (expectedType) {\n\t\tcase \"boolean\":\n\t\t\treturn typeof value === \"boolean\"\n\t\tcase \"decimal\":\n\t\t\treturn (\n\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\tvalue instanceof types.BigDecimal\n\t\t\t)\n\t\tcase \"varint\":\n\t\t\treturn (\n\t\t\t\ttypeof value === \"bigint\" ||\n\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\tvalue instanceof types.Integer\n\t\t\t)\n\t\tcase \"timestamp\":\n\t\t\treturn (\n\t\t\t\tvalue instanceof Date ||\n\t\t\t\ttypeof value === \"number\" ||\n\t\t\t\ttypeof value === \"string\"\n\t\t\t)\n\t\tcase \"date\":\n\t\t\treturn typeof value === \"string\" || value instanceof types.LocalDate\n\t\tcase \"time\":\n\t\t\treturn typeof value === \"string\" || value instanceof types.LocalTime\n\t\tcase \"uuid\":\n\t\t\treturn typeof value === \"string\" || value instanceof types.Uuid\n\t\tcase \"timeuuid\":\n\t\t\treturn typeof value === \"string\" || value instanceof types.TimeUuid\n\t\tcase \"blob\":\n\t\t\treturn Buffer.isBuffer(value) || value instanceof Uint8Array\n\t}\n\n\tif (expectedType.startsWith(\"list<\") || expectedType.startsWith(\"set<\")) {\n\t\treturn Array.isArray(value) || value instanceof Set\n\t}\n\tif (expectedType.startsWith(\"map<\")) {\n\t\treturn (\n\t\t\ttypeof value === \"object\" && !Array.isArray(value) && value !== null\n\t\t)\n\t}\n\n\treturn false\n}\n\nexport default function typeChecker(model: Model<any>, data: any): boolean {\n\tif (!data || typeof data !== \"object\" || Array.isArray(data)) {\n\t\tthrow new TypeError(\n\t\t\t`[${model.name}] Validation error: Data payload must be an object`,\n\t\t)\n\t}\n\n\tconst fields = model.schema.fields\n\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (!isValidFieldName(fields, key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`[${model.name}] Validation error: Field '${key}' does not exist in schema`,\n\t\t\t)\n\t\t}\n\n\t\tconst fieldConfig = fields[key]\n\t\tconst expectedType = (fieldConfig.type || \"text\").toLowerCase()\n\n\t\tif (!isValidValue(value, expectedType)) {\n\t\t\tconst receivedType = Array.isArray(value) ? \"array\" : typeof value\n\t\t\tthrow new TypeError(\n\t\t\t\t`[${model.name}] Validation error: Invalid type for field '${key}'. ` +\n\t\t\t\t\t`Expected[${expectedType}], but received [${receivedType}]`,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn true\n}\n","import type { Model } from \"../model\"\nimport typeChecker from \"../utils/typeChecker\"\n\nexport class Result<TDoc = any> {\n\tconstructor(data: TDoc, model: Model<TDoc>) {\n\t\tif (data == null) {\n\t\t\tthrow new Error(\"Cannot create Result with null or undefined data\")\n\t\t}\n\n\t\tif (typeof data !== \"object\" || Array.isArray(data)) {\n\t\t\tthrow new Error(\"Result data must be an object\")\n\t\t}\n\n\t\tObject.assign(this, data)\n\n\t\tObject.defineProperty(this, \"_model\", {\n\t\t\tvalue: model,\n\t\t\tenumerable: false,\n\t\t\twritable: false,\n\t\t\tconfigurable: false,\n\t\t})\n\t}\n\n\t_model: Model<TDoc>\n\n\tasync save() {\n\t\ttry {\n\t\t\tconst data = this.toRaw()\n\n\t\t\ttypeChecker(this._model, data)\n\n\t\t\treturn await this._model.update(data as any)\n\t\t} catch (error: any) {\n\t\t\tthrow new Error(`Failed to save result: ${error.message}`)\n\t\t}\n\t}\n\n\tasync delete() {\n\t\ttry {\n\t\t\treturn await this._model.delete(this.toRaw() as any)\n\t\t} catch (error: any) {\n\t\t\tthrow new Error(`Failed to delete result: ${error.message}`)\n\t\t}\n\t}\n\n\ttoRaw(): TDoc {\n\t\tconst raw: any = {}\n\n\t\tfor (const key in this) {\n\t\t\tif (key === \"_model\") continue\n\n\t\t\tif (this.propertyIsEnumerable(key)) {\n\t\t\t\tconst value = (this as any)[key]\n\n\t\t\t\ttry {\n\t\t\t\t\tJSON.stringify(value)\n\t\t\t\t\traw[key] = value\n\t\t\t\t} catch (error) {\n\t\t\t\t\traw[key] = String(value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn raw as TDoc\n\t}\n\n\tisValid(): boolean {\n\t\ttry {\n\t\t\ttypeChecker(this._model, this.toRaw())\n\t\t\treturn true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tgetChangedFields(original: Partial<TDoc>): (keyof TDoc)[] {\n\t\tconst current = this.toRaw() as Record<string, any>\n\t\tconst changed: (keyof TDoc)[] = []\n\n\t\tfor (const key in current) {\n\t\t\tif (!(key in original) || current[key] !== (original as any)[key]) {\n\t\t\t\tchanged.push(key as keyof TDoc)\n\t\t\t}\n\t\t}\n\n\t\treturn changed\n\t}\n}\n\nexport default Result\n","export default function fillDefaults(schema: any, data: any) {\n\tconst defaults = schema.options?.defaults\n\n\tif (!defaults || Object.keys(defaults).length === 0) {\n\t\treturn data\n\t}\n\n\tlet needsDefaults = false\n\n\tfor (const key in defaults) {\n\t\tif (data[key] == null) {\n\t\t\tneedsDefaults = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif (!needsDefaults) {\n\t\treturn data\n\t}\n\n\tconst result = Object.assign({}, data)\n\n\tfor (const key in defaults) {\n\t\tif (result[key] == null) {\n\t\t\tresult[key] = defaults[key]\n\t\t}\n\t}\n\n\treturn result\n}\n","import type { QueryOptions } from \"../types\"\nimport type Model from \"../model\"\nimport queryParser from \"../utils/queryParser\"\n\nexport default function (this: Model, query: any, options?: QueryOptions) {\n\tquery = queryParser(this, query)\n\n\tconst operation = async () => {\n\t\tlet result = await this.mapper.get(query)\n\n\t\tif (!result) {\n\t\t\treturn null\n\t\t}\n\n\t\tresult = this._wrap(result)\n\n\t\tif (options?.raw === true) {\n\t\t\treturn result.toRaw()\n\t\t}\n\n\t\treturn result\n\t}\n\n\treturn this.driver.executeWithRetry(operation, `findOne on ${this.name}`)\n}\n","import type Model from \"../model\"\nimport type { mapping } from \"cassandra-driver/lib/mapping\"\nimport type { Query, QueryOptions } from \"../types\"\nimport queryParser from \"../utils/queryParser\"\n\nexport default async function findOP<TDoc>(\n\tthis: Model<TDoc>,\n\tquery: Query<TDoc> = {},\n\toptions?: QueryOptions,\n) {\n\tconst { $limit, $orderby, ...rest } = query\n\n\tlet parsedQuery = queryParser(this, rest)\n\n\tconst docInfo: mapping.FindDocInfo = {}\n\n\tif ($limit !== undefined) {\n\t\tif (typeof $limit !== \"number\" || $limit <= 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`{$limit} operator must be a number greater than 0`,\n\t\t\t)\n\t\t}\n\t\tdocInfo.limit = $limit\n\t}\n\n\tif ($orderby !== undefined) {\n\t\tdocInfo.orderBy = $orderby as Record<string, \"asc\" | \"desc\">\n\t}\n\n\tconst operation = async () => {\n\t\tconst result = await this.mapper.find(parsedQuery, docInfo)\n\t\tconst rows = result.toArray()\n\n\t\tif (options?.raw === true) {\n\t\t\treturn rows\n\t\t}\n\n\t\treturn rows.map((row) => this._wrap(row))\n\t}\n\n\treturn this.driver.executeWithRetry(operation, `find on ${this.name}`)\n}\n","import type Model from \"../model\"\nimport fillDefaults from \"../utils/fillDefaults\"\nimport typeChecker from \"../utils/typeChecker\"\n\nexport default async function (this: Model, query: any) {\n\tquery = fillDefaults(this.schema, query)\n\n\ttypeChecker(this, query)\n\n\tif (typeof query.__v !== \"undefined\") {\n\t\tif (Number.isNaN(query.__v)) {\n\t\t\tquery.__v = 0\n\t\t} else {\n\t\t\tquery.__v = query.__v + 1\n\t\t}\n\t}\n\n\tconst operation = async () => {\n\t\tawait this.mapper.update(query)\n\t\treturn this._wrap(query)\n\t}\n\n\treturn this.driver.executeWithRetry(operation, `update on ${this.name}`)\n}\n","import type Model from \"../model\"\n\nexport default async function (this: Model, query: any) {\n\tconst operation = async () => {\n\t\treturn await this.mapper.remove(query)\n\t}\n\n\treturn this.driver.executeWithRetry(operation, `delete on ${this.name}`)\n}\n","import type Model from \"../model\"\n\nexport default async function (this: Model, timeoutMs: number = 60000) {\n\tconst cql = `SELECT COUNT(1) FROM ${this.driver.config.keyspace}.${this.schema.table_name}`\n\n\tconst queryOptions = {\n\t\tprepare: true,\n\t\treadTimeout: timeoutMs,\n\t}\n\n\tconst operation = async () => {\n\t\tconst result = await this.driver.client.execute(cql, [], queryOptions)\n\n\t\treturn result.rows[0].count.toNumber()\n\t}\n\n\treturn this.driver.executeWithRetry(operation, `countAll on ${this.name}`)\n}\n","import type Model from \"../model\"\n\nexport default async function (this: Model) {\n\tconst cql = `\n\t\t\tSELECT table_name\n\t\t\tFROM system_schema.tables\n\t\t\tWHERE keyspace_name = ?\n\t\t\tAND table_name = ?\n\t\t`\n\n\ttry {\n\t\tconst result = await this.driver.client.execute(\n\t\t\tcql,\n\t\t\t[this.driver.config.keyspace, this.schema.table_name],\n\t\t\t{\n\t\t\t\tprepare: true,\n\t\t\t},\n\t\t)\n\n\t\treturn result.rows.length > 0\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Failed to check if table \"${this.schema.table_name}\" exists:`,\n\t\t\terror,\n\t\t)\n\n\t\treturn false\n\t}\n}\n","import type Model from \"../model\"\n\nexport default function (model: Model): string {\n\tconst desc = model.schema\n\tconst tableName = desc.table_name\n\tconst keyspace = model.driver.config.keyspace\n\tconst fields = desc.fields\n\tconst key = desc.keys\n\tconst clusteringOrder = desc.clustering_order\n\n\tlet columnsDef = \"\"\n\n\tfor (const fieldName in fields) {\n\t\tconst field = fields[fieldName]\n\t\tconst typeStr = typeof field === \"string\" ? field : (field as any)?.type\n\n\t\tif (!typeStr) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid field type for \"${fieldName}\" in model \"${tableName}\"`,\n\t\t\t)\n\t\t}\n\n\t\tcolumnsDef += `\"${fieldName}\" ${typeStr.toUpperCase()}, `\n\t}\n\n\tlet pkDef = \"\"\n\n\tif (typeof key === \"string\") {\n\t\tpkDef = `\"${key}\"`\n\t} else if (Array.isArray(key) && key.length > 0) {\n\t\tconst first = key[0]\n\n\t\tif (Array.isArray(first)) {\n\t\t\tpkDef = `(${first.map((k) => `\"${k}\"`).join(\", \")})`\n\t\t} else {\n\t\t\tpkDef = `\"${first}\"`\n\t\t}\n\n\t\tfor (let i = 1; i < key.length; i++) {\n\t\t\tpkDef += `, \"${key[i]}\"`\n\t\t}\n\t} else {\n\t\tthrow new Error(\n\t\t\t`Missing or invalid primary key in model \"${tableName}\"`,\n\t\t)\n\t}\n\n\tlet clusterClause = \"\"\n\n\tif (clusteringOrder) {\n\t\tlet orderDef = \"\"\n\n\t\tfor (const col in clusteringOrder) {\n\t\t\tif (orderDef !== \"\") {\n\t\t\t\torderDef += \", \"\n\t\t\t}\n\n\t\t\torderDef += `\"${col}\" ${(clusteringOrder[col] as string).toUpperCase()}`\n\t\t}\n\t\tif (orderDef !== \"\") {\n\t\t\tclusterClause = ` WITH CLUSTERING ORDER BY (${orderDef})`\n\t\t}\n\t}\n\n\treturn `CREATE TABLE IF NOT EXISTS ${keyspace}.${tableName} (${columnsDef}PRIMARY KEY (${pkDef}))${clusterClause}`\n}\n","import type Model from \"../model\"\nimport generateCreateTableCQL from \"../cql_gen/create_table\"\n\nexport default async function syncOP(this: Model) {\n\tconst tableExists = await this._tableExists()\n\n\tif (tableExists) {\n\t\treturn\n\t}\n\n\ttry {\n\t\tawait this.driver.client.execute(generateCreateTableCQL(this))\n\n\t\tconsole.log(`Table \"${this.schema.table_name}\" created successfully`)\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Failed to create table \"${this.schema.table_name}\":`,\n\t\t\terror,\n\t\t)\n\t\tthrow error\n\t}\n}\n","import ScyllaClient from \"..\"\nimport { Result } from \"../result\"\n\nimport fillDefaults from \"../utils/fillDefaults\"\n\nimport { mapping } from \"cassandra-driver/lib/mapping\"\nimport type { DocumentResult, Query, QueryOptions } from \"../types\"\nimport type { Schema } from \"../schema\"\n\nimport findOneOP from \"../operations/findOne\"\nimport findOP from \"../operations/find\"\nimport updateOP from \"../operations/update\"\nimport deleteOP from \"../operations/delete\"\nimport countAllOP from \"../operations/countAll\"\n\nimport tableExistsOP from \"../operations/tableExists\"\nimport syncOP from \"../operations/sync\"\n\nexport class Model<TDoc = any> {\n\tname: string\n\tschema: Schema<any>\n\tdriver: ScyllaClient\n\tmapper: mapping.ModelMapper\n\n\tconstructor(name: string, schema: Schema<any>) {\n\t\tthis.name = name\n\t\tthis.schema = schema\n\n\t\tif (!Array.isArray(this.schema.keys)) {\n\t\t\tthrow new Error(`[${this.name}] model has missing \"keys\" array`)\n\t\t}\n\t\tif (!this.schema.table_name) {\n\t\t\tthrow new Error(`[${this.name}] model has missing \"table_name\"`)\n\t\t}\n\t\tif (!this.schema.fields || typeof this.schema.fields !== \"object\") {\n\t\t\tthrow new Error(\n\t\t\t\t`[${this.name}] model has missing or invalid \"fields\"`,\n\t\t\t)\n\t\t}\n\t}\n\n\tcreate = (data: Partial<TDoc>) => this._wrap(data)\n\n\tfind: {\n\t\t(\n\t\t\tquery: Query<TDoc>,\n\t\t\toptions: QueryOptions & { raw: true },\n\t\t): Promise<TDoc[]>\n\t\t(\n\t\t\tquery?: Query<TDoc>,\n\t\t\toptions?: QueryOptions,\n\t\t): Promise<DocumentResult<TDoc>[]>\n\t} = findOP.bind(this)\n\n\tfindOne: {\n\t\t(\n\t\t\tquery: Query<TDoc>,\n\t\t\toptions: QueryOptions & { raw: true },\n\t\t): Promise<TDoc>\n\t\t(\n\t\t\tquery?: Query<TDoc>,\n\t\t\toptions?: QueryOptions,\n\t\t): Promise<DocumentResult<TDoc>>\n\t} = findOneOP.bind(this)\n\n\tupdate: (query: Query<TDoc>) => Promise<DocumentResult<TDoc>> =\n\t\tupdateOP.bind(this)\n\n\tdelete: (query: Query<TDoc>) => Promise<mapping.Result> =\n\t\tdeleteOP.bind(this)\n\n\tcountAll: () => Promise<number> = countAllOP.bind(this)\n\n\t_sync: typeof syncOP = syncOP.bind(this)\n\t_tableExists: typeof tableExistsOP = tableExistsOP.bind(this)\n\n\t_wrap(row: any): DocumentResult<TDoc> | null {\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\n\t\trow = fillDefaults(this.schema, row)\n\n\t\treturn new Result<TDoc>(row, this) as DocumentResult<TDoc>\n\t}\n\n\t_connect(driver: ScyllaClient) {\n\t\tthis.driver = driver\n\t\tthis.mapper = driver.mapper.forModel(this.name)\n\t}\n}\n\nexport default Model\n","import type {\n\tClient as T_CassandraClient,\n\tClientOptions as T_CassandraClientOptions,\n\tmapping as T_CassandraMapping,\n} from \"cassandra-driver\"\nimport type { ClientConfig } from \"./types\"\n\n//@ts-ignore\nimport path from \"node:path\"\n//@ts-ignore\nimport Cassandra from \"cassandra-driver\"\nimport loadSchemas from \"./utils/loadSchemas\"\nimport buildMapper from \"./utils/buildMapper\"\n\nimport { Model } from \"./model\"\nimport { InferDocument } from \"./types\"\n\nconst DEFAULT_MAX_RETRIES = 3\nconst DEFAULT_RETRY_DELAY = 1000\nconst { SCYLLA_CONTACT_POINTS, SCYLLA_LOCAL_DATA_CENTER, SCYLLA_KEYSPACE } =\n\tprocess.env\n\nexport default class ScyllaClient {\n\tconstructor(config: ClientConfig = {}) {\n\t\tthis.config = {\n\t\t\tmodelsPath: path.resolve(__dirname, \"../../db\"),\n\t\t\tcontactPoints:\n\t\t\t\t(config.contactPoints ?? SCYLLA_CONTACT_POINTS)\n\t\t\t\t\t? SCYLLA_CONTACT_POINTS.split(\",\")\n\t\t\t\t\t: [\"127.0.0.1\"],\n\t\t\tlocalDataCenter:\n\t\t\t\tconfig.localDataCenter ??\n\t\t\t\tSCYLLA_LOCAL_DATA_CENTER ??\n\t\t\t\t\"datacenter1\",\n\t\t\tkeyspace: config.keyspace ?? SCYLLA_KEYSPACE ?? \"default\",\n\t\t\tport: 9042,\n\t\t\tmaxRetries: DEFAULT_MAX_RETRIES,\n\t\t\tretryDelay: DEFAULT_RETRY_DELAY,\n\t\t\t...config,\n\t\t}\n\n\t\tconst clientOptions: T_CassandraClientOptions = {\n\t\t\tcontactPoints: this.config.contactPoints,\n\t\t\tlocalDataCenter: this.config.localDataCenter,\n\t\t\tkeyspace: this.config.keyspace,\n\t\t\tprotocolOptions: {\n\t\t\t\tport: this.config.port,\n\t\t\t},\n\t\t}\n\n\t\tif (this.config.pooling) {\n\t\t\tclientOptions.pooling = this.config.pooling\n\t\t}\n\n\t\tthis.client = new Cassandra.Client(clientOptions)\n\t}\n\n\tconfig: ClientConfig\n\tclient: T_CassandraClient\n\tmapper: T_CassandraMapping.Mapper\n\tmodels: Map<string, Model<any>> = new Map()\n\n\tasync initialize(options: { sync?: boolean } = {}) {\n\t\tlet models: Model<any>[]\n\n\t\ttry {\n\t\t\tmodels = await loadSchemas(this.config.modelsPath)\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to load models: ${error.message}`)\n\t\t}\n\n\t\tmodels = models.filter((schema) => schema instanceof Model)\n\n\t\tthis.mapper = new Cassandra.mapping.Mapper(this.client, {\n\t\t\tmodels: buildMapper(models),\n\t\t})\n\n\t\tfor (let model of models) {\n\t\t\tmodel._connect(this)\n\n\t\t\tthis.models.set(\n\t\t\t\tmodel.name,\n\t\t\t\tmodel as Model<InferDocument<typeof model.schema>>,\n\t\t\t)\n\n\t\t\tif (options?.sync === true) {\n\t\t\t\tawait model._sync()\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(\"Connecting to ScyllaDB\")\n\t\tawait this.connectWithRetry()\n\t\tconsole.log(\"ScyllaDB Connected\")\n\t}\n\n\tprivate async connectWithRetry(): Promise<void> {\n\t\tlet lastError: Error | null = null\n\n\t\tfor (let attempt = 1; attempt <= this.config.maxRetries!; attempt++) {\n\t\t\ttry {\n\t\t\t\tawait this.client.connect()\n\t\t\t\treturn\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Connection attempt ${attempt} failed: ${error.message}`,\n\t\t\t\t)\n\n\t\t\t\tif (attempt < this.config.maxRetries!) {\n\t\t\t\t\tconsole.log(`Retrying in ${this.config.retryDelay}ms...`)\n\t\t\t\t\tawait this.delay(this.config.retryDelay!)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`Failed to connect to ScyllaDB after ${this.config.maxRetries} attempts: ${lastError?.message}`,\n\t\t)\n\t}\n\n\tprivate delay(ms: number): Promise<void> {\n\t\treturn new Promise((resolve) => setTimeout(resolve, ms))\n\t}\n\n\tasync shutdown(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.client.shutdown()\n\t\t\tconsole.log(\"ScyllaDB connection closed\")\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error shutting down ScyllaDB connection:\", error)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tasync executeWithRetry<T>(\n\t\toperation: () => Promise<T>,\n\t\toperationName: string = \"operation\",\n\t): Promise<T> {\n\t\tlet lastError: Error | null = null\n\n\t\tfor (let attempt = 1; attempt <= this.config.maxRetries!; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await operation()\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error\n\n\t\t\t\t// check if error is retryable\n\t\t\t\tif (\n\t\t\t\t\tthis.isRetryableError(error) &&\n\t\t\t\t\tattempt < this.config.maxRetries!\n\t\t\t\t) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`Operation ${operationName} attempt ${attempt} failed: ${error.message}`,\n\t\t\t\t\t)\n\t\t\t\t\tconsole.log(`Retrying in ${this.config.retryDelay}ms...`)\n\n\t\t\t\t\tawait this.delay(this.config.retryDelay!)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// if not retryable or last attempt, throw\n\t\t\t\tthrow error\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`Operation ${operationName} failed after ${this.config.maxRetries} attempts: ${lastError?.message}`,\n\t\t)\n\t}\n\n\tprivate isRetryableError(error: any): boolean {\n\t\t// retry on network errors, timeouts, and certain ScyllaDB errors\n\t\tconst retryableMessages = [\n\t\t\t\"timeout\",\n\t\t\t\"connection\",\n\t\t\t\"network\",\n\t\t\t\"unavailable\",\n\t\t\t\"overloaded\",\n\t\t\t\"no hosts available\",\n\t\t]\n\n\t\tconst errorMessage = error.message?.toLowerCase() || \"\"\n\n\t\treturn retryableMessages.some((msg) => errorMessage.includes(msg))\n\t}\n}\n"],"mappings":";;;;AAGA,IAAA,sBAAe,OAAO,aAAqC;AAC1D,KAAI,OAAO,aAAa,SACvB,QAAO,EAAE;AAGV,KAAI,CAAC,GAAG,WAAW,SAAS,EAAE;AAC7B,UAAQ,KACP,4BAA4B,SAAS,iCACrC;AACD,SAAO,EAAE;;CAGV,IAAI,UAAU,EAAE;CAEhB,IAAI,QAAQ,MAAM,GAAG,SAAS,QAAQ,SAAS;AAE/C,SAAQ,MAAM,QAAQ,SAAS,KAAK,SAAS,MAAM,IAAI,KAAK,SAAS,MAAM,CAAC;AAE5E,YAAW,MAAM,QAAQ,OAAO;EAC/B,MAAM,OAAO,KAAK,QAAQ,OAAO,GAAG;EACpC,MAAM,YAAY,KAAK,KAAK,UAAU,K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3.0",
|
|
4
4
|
"description": "An ODM for ScyllaDB",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "RageStudio",
|
|
7
7
|
"type": "module",
|
|
8
|
-
"main": "
|
|
8
|
+
"main": "dist/index.mjs",
|
|
9
|
+
"module": "dist/index.mjs",
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.mjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
9
20
|
"publishConfig": {
|
|
10
21
|
"access": "public"
|
|
11
22
|
},
|
|
12
23
|
"dependencies": {
|
|
13
24
|
"cassandra-driver": "^4.8.0"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsdown",
|
|
28
|
+
"prepublishOnly": "npm run build"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^25.6.0",
|
|
32
|
+
"tsdown": "^0.21.10",
|
|
33
|
+
"typescript": "^6.0.3"
|
|
14
34
|
}
|
|
15
35
|
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
|
|
3
|
-
export default function (model: Model): string {
|
|
4
|
-
const desc = model.schema
|
|
5
|
-
const tableName = desc.table_name
|
|
6
|
-
const keyspace = model.driver.config.keyspace
|
|
7
|
-
const fields = desc.fields
|
|
8
|
-
const key = desc.keys
|
|
9
|
-
const clusteringOrder = desc.clustering_order
|
|
10
|
-
|
|
11
|
-
let columnsDef = ""
|
|
12
|
-
|
|
13
|
-
for (const fieldName in fields) {
|
|
14
|
-
const field = fields[fieldName]
|
|
15
|
-
const typeStr = typeof field === "string" ? field : (field as any)?.type
|
|
16
|
-
|
|
17
|
-
if (!typeStr) {
|
|
18
|
-
throw new Error(
|
|
19
|
-
`Invalid field type for "${fieldName}" in model "${tableName}"`,
|
|
20
|
-
)
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
columnsDef += `"${fieldName}" ${typeStr.toUpperCase()}, `
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
let pkDef = ""
|
|
27
|
-
|
|
28
|
-
if (typeof key === "string") {
|
|
29
|
-
pkDef = `"${key}"`
|
|
30
|
-
} else if (Array.isArray(key) && key.length > 0) {
|
|
31
|
-
const first = key[0]
|
|
32
|
-
|
|
33
|
-
if (Array.isArray(first)) {
|
|
34
|
-
pkDef = `(${first.map((k) => `"${k}"`).join(", ")})`
|
|
35
|
-
} else {
|
|
36
|
-
pkDef = `"${first}"`
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
for (let i = 1; i < key.length; i++) {
|
|
40
|
-
pkDef += `, "${key[i]}"`
|
|
41
|
-
}
|
|
42
|
-
} else {
|
|
43
|
-
throw new Error(
|
|
44
|
-
`Missing or invalid primary key in model "${tableName}"`,
|
|
45
|
-
)
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
let clusterClause = ""
|
|
49
|
-
|
|
50
|
-
if (clusteringOrder) {
|
|
51
|
-
let orderDef = ""
|
|
52
|
-
|
|
53
|
-
for (const col in clusteringOrder) {
|
|
54
|
-
if (orderDef !== "") {
|
|
55
|
-
orderDef += ", "
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
orderDef += `"${col}" ${(clusteringOrder[col] as string).toUpperCase()}`
|
|
59
|
-
}
|
|
60
|
-
if (orderDef !== "") {
|
|
61
|
-
clusterClause = ` WITH CLUSTERING ORDER BY (${orderDef})`
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
return `CREATE TABLE IF NOT EXISTS ${keyspace}.${tableName} (${columnsDef}PRIMARY KEY (${pkDef}))${clusterClause}`
|
|
66
|
-
}
|
package/src/index.ts
DELETED
|
@@ -1,186 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
Client as T_CassandraClient,
|
|
3
|
-
ClientOptions as T_CassandraClientOptions,
|
|
4
|
-
mapping as T_CassandraMapping,
|
|
5
|
-
} from "cassandra-driver"
|
|
6
|
-
import type { ClientConfig } from "./types"
|
|
7
|
-
|
|
8
|
-
//@ts-ignore
|
|
9
|
-
import path from "node:path"
|
|
10
|
-
//@ts-ignore
|
|
11
|
-
import Cassandra from "cassandra-driver"
|
|
12
|
-
import loadSchemas from "./utils/loadSchemas"
|
|
13
|
-
import buildMapper from "./utils/buildMapper"
|
|
14
|
-
|
|
15
|
-
import { Model } from "./model"
|
|
16
|
-
import { InferDocument } from "./types"
|
|
17
|
-
|
|
18
|
-
const DEFAULT_MAX_RETRIES = 3
|
|
19
|
-
const DEFAULT_RETRY_DELAY = 1000
|
|
20
|
-
const { SCYLLA_CONTACT_POINTS, SCYLLA_LOCAL_DATA_CENTER, SCYLLA_KEYSPACE } =
|
|
21
|
-
process.env
|
|
22
|
-
|
|
23
|
-
export default class ScyllaClient {
|
|
24
|
-
constructor(config: ClientConfig = {}) {
|
|
25
|
-
this.config = {
|
|
26
|
-
modelsPath: path.resolve(__dirname, "../../db"),
|
|
27
|
-
contactPoints:
|
|
28
|
-
(config.contactPoints ?? SCYLLA_CONTACT_POINTS)
|
|
29
|
-
? SCYLLA_CONTACT_POINTS.split(",")
|
|
30
|
-
: ["127.0.0.1"],
|
|
31
|
-
localDataCenter:
|
|
32
|
-
config.localDataCenter ??
|
|
33
|
-
SCYLLA_LOCAL_DATA_CENTER ??
|
|
34
|
-
"datacenter1",
|
|
35
|
-
keyspace: config.keyspace ?? SCYLLA_KEYSPACE ?? "default",
|
|
36
|
-
port: 9042,
|
|
37
|
-
maxRetries: DEFAULT_MAX_RETRIES,
|
|
38
|
-
retryDelay: DEFAULT_RETRY_DELAY,
|
|
39
|
-
...config,
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
const clientOptions: T_CassandraClientOptions = {
|
|
43
|
-
contactPoints: this.config.contactPoints,
|
|
44
|
-
localDataCenter: this.config.localDataCenter,
|
|
45
|
-
keyspace: this.config.keyspace,
|
|
46
|
-
protocolOptions: {
|
|
47
|
-
port: this.config.port,
|
|
48
|
-
},
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if (this.config.pooling) {
|
|
52
|
-
clientOptions.pooling = this.config.pooling
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
this.client = new Cassandra.Client(clientOptions)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
config: ClientConfig
|
|
59
|
-
client: T_CassandraClient
|
|
60
|
-
mapper: T_CassandraMapping.Mapper
|
|
61
|
-
models: Map<string, Model<any>> = new Map()
|
|
62
|
-
|
|
63
|
-
async initialize(options: { sync?: boolean } = {}) {
|
|
64
|
-
let models: Model<any>[]
|
|
65
|
-
|
|
66
|
-
try {
|
|
67
|
-
models = await loadSchemas(this.config.modelsPath)
|
|
68
|
-
} catch (error) {
|
|
69
|
-
throw new Error(`Failed to load models: ${error.message}`)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
models = models.filter((schema) => schema instanceof Model)
|
|
73
|
-
|
|
74
|
-
this.mapper = new Cassandra.mapping.Mapper(this.client, {
|
|
75
|
-
models: buildMapper(models),
|
|
76
|
-
})
|
|
77
|
-
|
|
78
|
-
for (let model of models) {
|
|
79
|
-
model._connect(this)
|
|
80
|
-
|
|
81
|
-
this.models.set(
|
|
82
|
-
model.name,
|
|
83
|
-
model as Model<InferDocument<typeof model.schema>>,
|
|
84
|
-
)
|
|
85
|
-
|
|
86
|
-
if (options?.sync === true) {
|
|
87
|
-
await model._sync()
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
console.log("Connecting to ScyllaDB")
|
|
92
|
-
await this.connectWithRetry()
|
|
93
|
-
console.log("ScyllaDB Connected")
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
private async connectWithRetry(): Promise<void> {
|
|
97
|
-
let lastError: Error | null = null
|
|
98
|
-
|
|
99
|
-
for (let attempt = 1; attempt <= this.config.maxRetries!; attempt++) {
|
|
100
|
-
try {
|
|
101
|
-
await this.client.connect()
|
|
102
|
-
return
|
|
103
|
-
} catch (error) {
|
|
104
|
-
lastError = error
|
|
105
|
-
console.warn(
|
|
106
|
-
`Connection attempt ${attempt} failed: ${error.message}`,
|
|
107
|
-
)
|
|
108
|
-
|
|
109
|
-
if (attempt < this.config.maxRetries!) {
|
|
110
|
-
console.log(`Retrying in ${this.config.retryDelay}ms...`)
|
|
111
|
-
await this.delay(this.config.retryDelay!)
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
throw new Error(
|
|
117
|
-
`Failed to connect to ScyllaDB after ${this.config.maxRetries} attempts: ${lastError?.message}`,
|
|
118
|
-
)
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
private delay(ms: number): Promise<void> {
|
|
122
|
-
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async shutdown(): Promise<void> {
|
|
126
|
-
try {
|
|
127
|
-
await this.client.shutdown()
|
|
128
|
-
console.log("ScyllaDB connection closed")
|
|
129
|
-
} catch (error) {
|
|
130
|
-
console.error("Error shutting down ScyllaDB connection:", error)
|
|
131
|
-
throw error
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
async executeWithRetry<T>(
|
|
136
|
-
operation: () => Promise<T>,
|
|
137
|
-
operationName: string = "operation",
|
|
138
|
-
): Promise<T> {
|
|
139
|
-
let lastError: Error | null = null
|
|
140
|
-
|
|
141
|
-
for (let attempt = 1; attempt <= this.config.maxRetries!; attempt++) {
|
|
142
|
-
try {
|
|
143
|
-
return await operation()
|
|
144
|
-
} catch (error) {
|
|
145
|
-
lastError = error
|
|
146
|
-
|
|
147
|
-
// check if error is retryable
|
|
148
|
-
if (
|
|
149
|
-
this.isRetryableError(error) &&
|
|
150
|
-
attempt < this.config.maxRetries!
|
|
151
|
-
) {
|
|
152
|
-
console.warn(
|
|
153
|
-
`Operation ${operationName} attempt ${attempt} failed: ${error.message}`,
|
|
154
|
-
)
|
|
155
|
-
console.log(`Retrying in ${this.config.retryDelay}ms...`)
|
|
156
|
-
|
|
157
|
-
await this.delay(this.config.retryDelay!)
|
|
158
|
-
continue
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// if not retryable or last attempt, throw
|
|
162
|
-
throw error
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
throw new Error(
|
|
167
|
-
`Operation ${operationName} failed after ${this.config.maxRetries} attempts: ${lastError?.message}`,
|
|
168
|
-
)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
private isRetryableError(error: any): boolean {
|
|
172
|
-
// retry on network errors, timeouts, and certain ScyllaDB errors
|
|
173
|
-
const retryableMessages = [
|
|
174
|
-
"timeout",
|
|
175
|
-
"connection",
|
|
176
|
-
"network",
|
|
177
|
-
"unavailable",
|
|
178
|
-
"overloaded",
|
|
179
|
-
"no hosts available",
|
|
180
|
-
]
|
|
181
|
-
|
|
182
|
-
const errorMessage = error.message?.toLowerCase() || ""
|
|
183
|
-
|
|
184
|
-
return retryableMessages.some((msg) => errorMessage.includes(msg))
|
|
185
|
-
}
|
|
186
|
-
}
|
package/src/model/index.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import ScyllaClient from ".."
|
|
2
|
-
import { Result } from "../result"
|
|
3
|
-
|
|
4
|
-
import fillDefaults from "../utils/fillDefaults"
|
|
5
|
-
|
|
6
|
-
import { mapping } from "cassandra-driver/lib/mapping"
|
|
7
|
-
import type { DocumentResult, Query, QueryOptions } from "../types"
|
|
8
|
-
import type { Schema } from "../schema"
|
|
9
|
-
|
|
10
|
-
import findOneOP from "../operations/findOne"
|
|
11
|
-
import findOP from "../operations/find"
|
|
12
|
-
import updateOP from "../operations/update"
|
|
13
|
-
import deleteOP from "../operations/delete"
|
|
14
|
-
import countAllOP from "../operations/countAll"
|
|
15
|
-
|
|
16
|
-
import tableExistsOP from "../operations/tableExists"
|
|
17
|
-
import syncOP from "../operations/sync"
|
|
18
|
-
|
|
19
|
-
export class Model<TDoc = any> {
|
|
20
|
-
name: string
|
|
21
|
-
schema: Schema<any>
|
|
22
|
-
driver: ScyllaClient
|
|
23
|
-
mapper: mapping.ModelMapper
|
|
24
|
-
|
|
25
|
-
constructor(name: string, schema: Schema<any>) {
|
|
26
|
-
this.name = name
|
|
27
|
-
this.schema = schema
|
|
28
|
-
|
|
29
|
-
if (!Array.isArray(this.schema.keys)) {
|
|
30
|
-
throw new Error(`[${this.name}] model has missing "keys" array`)
|
|
31
|
-
}
|
|
32
|
-
if (!this.schema.table_name) {
|
|
33
|
-
throw new Error(`[${this.name}] model has missing "table_name"`)
|
|
34
|
-
}
|
|
35
|
-
if (!this.schema.fields || typeof this.schema.fields !== "object") {
|
|
36
|
-
throw new Error(
|
|
37
|
-
`[${this.name}] model has missing or invalid "fields"`,
|
|
38
|
-
)
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
create = (data: Partial<TDoc>) => this._wrap(data)
|
|
43
|
-
|
|
44
|
-
find: {
|
|
45
|
-
(
|
|
46
|
-
query: Query<TDoc>,
|
|
47
|
-
options: QueryOptions & { raw: true },
|
|
48
|
-
): Promise<TDoc[]>
|
|
49
|
-
(
|
|
50
|
-
query?: Query<TDoc>,
|
|
51
|
-
options?: QueryOptions,
|
|
52
|
-
): Promise<DocumentResult<TDoc>[]>
|
|
53
|
-
} = findOP.bind(this)
|
|
54
|
-
|
|
55
|
-
findOne: {
|
|
56
|
-
(
|
|
57
|
-
query: Query<TDoc>,
|
|
58
|
-
options: QueryOptions & { raw: true },
|
|
59
|
-
): Promise<TDoc>
|
|
60
|
-
(
|
|
61
|
-
query?: Query<TDoc>,
|
|
62
|
-
options?: QueryOptions,
|
|
63
|
-
): Promise<DocumentResult<TDoc>>
|
|
64
|
-
} = findOneOP.bind(this)
|
|
65
|
-
|
|
66
|
-
update: (query: Query<TDoc>) => Promise<DocumentResult<TDoc>> =
|
|
67
|
-
updateOP.bind(this)
|
|
68
|
-
|
|
69
|
-
delete: (query: Query<TDoc>) => Promise<mapping.Result> =
|
|
70
|
-
deleteOP.bind(this)
|
|
71
|
-
|
|
72
|
-
countAll: () => Promise<number> = countAllOP.bind(this)
|
|
73
|
-
|
|
74
|
-
_sync: typeof syncOP = syncOP.bind(this)
|
|
75
|
-
_tableExists: typeof tableExistsOP = tableExistsOP.bind(this)
|
|
76
|
-
|
|
77
|
-
_wrap(row: any): DocumentResult<TDoc> | null {
|
|
78
|
-
if (!row) {
|
|
79
|
-
return null
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
row = fillDefaults(this.schema, row)
|
|
83
|
-
|
|
84
|
-
return new Result<TDoc>(row, this) as DocumentResult<TDoc>
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
_connect(driver: ScyllaClient) {
|
|
88
|
-
this.driver = driver
|
|
89
|
-
this.mapper = driver.mapper.forModel(this.name)
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export default Model
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
|
|
3
|
-
export default async function (this: Model, timeoutMs: number = 60000) {
|
|
4
|
-
const cql = `SELECT COUNT(1) FROM ${this.driver.config.keyspace}.${this.schema.table_name}`
|
|
5
|
-
|
|
6
|
-
const queryOptions = {
|
|
7
|
-
prepare: true,
|
|
8
|
-
readTimeout: timeoutMs,
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
const operation = async () => {
|
|
12
|
-
const result = await this.driver.client.execute(cql, [], queryOptions)
|
|
13
|
-
|
|
14
|
-
return result.rows[0].count.toNumber()
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
return this.driver.executeWithRetry(operation, `countAll on ${this.name}`)
|
|
18
|
-
}
|
package/src/operations/delete.ts
DELETED
package/src/operations/find.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
import type { mapping } from "cassandra-driver/lib/mapping"
|
|
3
|
-
import type { Query, QueryOptions } from "../types"
|
|
4
|
-
import queryParser from "../utils/queryParser"
|
|
5
|
-
|
|
6
|
-
export default async function findOP<TDoc>(
|
|
7
|
-
this: Model<TDoc>,
|
|
8
|
-
query: Query<TDoc> = {},
|
|
9
|
-
options?: QueryOptions,
|
|
10
|
-
) {
|
|
11
|
-
const { $limit, $orderby, ...rest } = query
|
|
12
|
-
|
|
13
|
-
let parsedQuery = queryParser(this, rest)
|
|
14
|
-
|
|
15
|
-
const docInfo: mapping.FindDocInfo = {}
|
|
16
|
-
|
|
17
|
-
if ($limit !== undefined) {
|
|
18
|
-
if (typeof $limit !== "number" || $limit <= 0) {
|
|
19
|
-
throw new TypeError(
|
|
20
|
-
`{$limit} operator must be a number greater than 0`,
|
|
21
|
-
)
|
|
22
|
-
}
|
|
23
|
-
docInfo.limit = $limit
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
if ($orderby !== undefined) {
|
|
27
|
-
docInfo.orderBy = $orderby as Record<string, "asc" | "desc">
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const operation = async () => {
|
|
31
|
-
const result = await this.mapper.find(parsedQuery, docInfo)
|
|
32
|
-
const rows = result.toArray()
|
|
33
|
-
|
|
34
|
-
if (options?.raw === true) {
|
|
35
|
-
return rows
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
return rows.map((row) => this._wrap(row))
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
return this.driver.executeWithRetry(operation, `find on ${this.name}`)
|
|
42
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import type { QueryOptions } from "../types"
|
|
2
|
-
import type Model from "../model"
|
|
3
|
-
import queryParser from "../utils/queryParser"
|
|
4
|
-
|
|
5
|
-
export default function (this: Model, query: any, options?: QueryOptions) {
|
|
6
|
-
query = queryParser(this, query)
|
|
7
|
-
|
|
8
|
-
const operation = async () => {
|
|
9
|
-
let result = await this.mapper.get(query)
|
|
10
|
-
|
|
11
|
-
if (!result) {
|
|
12
|
-
return null
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
result = this._wrap(result)
|
|
16
|
-
|
|
17
|
-
if (options?.raw === true) {
|
|
18
|
-
return result.toRaw()
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
return result
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
return this.driver.executeWithRetry(operation, `findOne on ${this.name}`)
|
|
25
|
-
}
|
package/src/operations/sync.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
import generateCreateTableCQL from "../cql_gen/create_table"
|
|
3
|
-
|
|
4
|
-
export default async function syncOP(this: Model) {
|
|
5
|
-
const tableExists = await this._tableExists()
|
|
6
|
-
|
|
7
|
-
if (tableExists) {
|
|
8
|
-
return
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
try {
|
|
12
|
-
await this.driver.client.execute(generateCreateTableCQL(this))
|
|
13
|
-
|
|
14
|
-
console.log(`Table "${this.schema.table_name}" created successfully`)
|
|
15
|
-
} catch (error) {
|
|
16
|
-
console.error(
|
|
17
|
-
`Failed to create table "${this.schema.table_name}":`,
|
|
18
|
-
error,
|
|
19
|
-
)
|
|
20
|
-
throw error
|
|
21
|
-
}
|
|
22
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
|
|
3
|
-
export default async function (this: Model) {
|
|
4
|
-
const cql = `
|
|
5
|
-
SELECT table_name
|
|
6
|
-
FROM system_schema.tables
|
|
7
|
-
WHERE keyspace_name = ?
|
|
8
|
-
AND table_name = ?
|
|
9
|
-
`
|
|
10
|
-
|
|
11
|
-
try {
|
|
12
|
-
const result = await this.driver.client.execute(
|
|
13
|
-
cql,
|
|
14
|
-
[this.driver.config.keyspace, this.schema.table_name],
|
|
15
|
-
{
|
|
16
|
-
prepare: true,
|
|
17
|
-
},
|
|
18
|
-
)
|
|
19
|
-
|
|
20
|
-
return result.rows.length > 0
|
|
21
|
-
} catch (error) {
|
|
22
|
-
console.error(
|
|
23
|
-
`Failed to check if table "${this.schema.table_name}" exists:`,
|
|
24
|
-
error,
|
|
25
|
-
)
|
|
26
|
-
|
|
27
|
-
return false
|
|
28
|
-
}
|
|
29
|
-
}
|
package/src/operations/update.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import type Model from "../model"
|
|
2
|
-
import fillDefaults from "../utils/fillDefaults"
|
|
3
|
-
import typeChecker from "../utils/typeChecker"
|
|
4
|
-
|
|
5
|
-
export default async function (this: Model, query: any) {
|
|
6
|
-
query = fillDefaults(this.schema, query)
|
|
7
|
-
|
|
8
|
-
typeChecker(this, query)
|
|
9
|
-
|
|
10
|
-
if (typeof query.__v !== "undefined") {
|
|
11
|
-
if (Number.isNaN(query.__v)) {
|
|
12
|
-
query.__v = 0
|
|
13
|
-
} else {
|
|
14
|
-
query.__v = query.__v + 1
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const operation = async () => {
|
|
19
|
-
await this.mapper.update(query)
|
|
20
|
-
return this._wrap(query)
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
return this.driver.executeWithRetry(operation, `update on ${this.name}`)
|
|
24
|
-
}
|