{"id":17184,"library":"cassandra-codegen","title":"Cassandra Codegen","description":"Cassandra Codegen is a utility that generates TypeScript type definitions and type-safe mappers directly from a Cassandra or ScyllaDB database schema. Its current stable version is 0.0.11. The package releases updates on an irregular but active cadence, primarily addressing bug fixes, adding support for new Cassandra types, and enhancing generated type safety. A key differentiator is its ability to produce mappers that extend the functionality of `cassandra-driver`, offering improved type annotations for partition keys, clustering columns, and query operators. It automatically maps Cassandra types like `map` to TypeScript's `Record` and handles optionality/nullability for non-primary key columns in generated insert/retrieve types, aligning with typical driver behavior. The project draws inspiration from `kysely-codegen` for its schema-to-type generation approach.","status":"active","version":"0.0.11","language":"javascript","source_language":"en","source_url":"https://github.com/ramikg/cassandra-codegen","tags":["javascript","cassandra","scylladb","cql","typescript"],"install":[{"cmd":"npm install cassandra-codegen","lang":"bash","label":"npm"},{"cmd":"yarn add cassandra-codegen","lang":"bash","label":"yarn"},{"cmd":"pnpm add cassandra-codegen","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required runtime peer dependency for connecting to Cassandra and initializing the generated mappers. The package interacts directly with instances of `cassandra-driver.Client`.","package":"cassandra-driver","optional":false}],"imports":[{"note":"Initializes all generated mappers with a connected `cassandra-driver` client. Must be called once before using any mappers.","wrong":"const { initMappers } = require('cassandra-codegen');","symbol":"initMappers","correct":"import { initMappers } from 'cassandra-codegen';"},{"note":"This represents a dynamically generated mapper for a specific Cassandra table (e.g., `cyclist_category`). While the README indicates importing directly from `cassandra-codegen`, in practice, this often implies the generated code is compiled or re-exported, or that the path points to the actual generated file output by the CLI tool (e.g., `./generated/mykeyspace`). Always confirm the exact import path based on your `cassandra-codegen` CLI output configuration.","wrong":"import cyclistCategoryMapper from 'cassandra-codegen';","symbol":"cyclistCategoryMapper","correct":"import { cyclistCategoryMapper } from 'cassandra-codegen';"},{"note":"Provides type-safe wrappers for `cassandra-driver`'s query operators (e.g., `gte`, `lte`), used within mapper queries.","wrong":"import * as queryOperator from 'cassandra-codegen/queryOperator';","symbol":"queryOperator","correct":"import { queryOperator } from 'cassandra-codegen';"}],"quickstart":{"code":"import { initMappers, queryOperator } from 'cassandra-codegen';\nimport type { CyclistCategoryRow } from './generated/mykeyspace'; // Adjust path to your generated types\nimport { Client } from 'cassandra-driver';\n\n// 1. Configure and connect your cassandra-driver client\nconst cassandraClient = new Client({\n  contactPoints: ['127.0.0.1'], // Your Cassandra host\n  localDataCenter: 'datacenter1', // Your datacenter\n  credentials: { username: 'user', password: 'password' }, // Your credentials\n  keyspace: 'mykeyspace', // The keyspace you generated types for\n});\n\nasync function main() {\n  await cassandraClient.connect();\n  console.log('Cassandra client connected.');\n\n  // 2. Initialize the generated mappers with the connected client\n  await initMappers(cassandraClient);\n  console.log('Mappers initialized.');\n\n  // 3. Import and use a generated mapper (e.g., 'cyclistCategoryMapper')\n  // Assuming 'cyclistCategoryMapper' and 'CyclistCategoryRow' are exported from './generated/mykeyspace.ts'\n  // You must run the `cassandra-codegen` CLI tool first to generate these files.\n  const cyclistCategoryMapper: {\n    get: (criteria: { category: string; points: number }) => Promise<CyclistCategoryRow | null>;\n    find: (criteria: { category?: string; points?: number | { $gte?: number; $lte?: number } }) => Promise<CyclistCategoryRow[]>;\n    // ... other generated methods like insert, update, remove\n  } = {} as any; // Placeholder for actual generated mapper\n\n  console.log('\\n--- Fetching a specific cyclist category ---');\n  const specificCyclist = await cyclistCategoryMapper.get({\n    category: 'GC',\n    points: 100,\n  });\n  console.log('Retrieved:', specificCyclist);\n\n  console.log('\\n--- Finding cyclists using a query operator ---');\n  const filteredCyclists = await cyclistCategoryMapper.find({\n    category: 'GC',\n    points: queryOperator.gte(42), // Using a type-safe query operator\n  });\n  console.log('Filtered results:', filteredCyclists);\n\n  await cassandraClient.shutdown();\n  console.log('Cassandra client disconnected.');\n}\n\nmain().catch(console.error);\n\n/*\nTo run this example:\n1. Ensure Cassandra is running and your keyspace/table exists.\n2. Install dependencies: `npm install cassandra-codegen cassandra-driver @types/cassandra-driver`\n3. Generate types/mappers: `npm exec cassandra-codegen -- --host 127.0.0.1 --port 9042 --datacenter datacenter1 --username user --password password --keyspace mykeyspace --generate-ts-file --output-dir ./generated`\n4. Adjust the import path for `CyclistCategoryRow` and the mocked `cyclistCategoryMapper` to point to your generated file (e.g., `./generated/mykeyspace`).\n5. Run with `ts-node your-file.ts` (if `ts-node` is installed) or compile and run `tsc your-file.ts && node your-file.js`.\n*/","lang":"typescript","description":"This quickstart demonstrates how to set up `cassandra-codegen` in a TypeScript project: connecting a Cassandra client, initializing the generated mappers, and then performing basic `get` and `find` operations using a generated mapper and type-safe query operators."},"warnings":[{"fix":"Review generated types and adjust type assertions or narrowing logic where `unknown` is now used. For example, `(value as string)` or `if (typeof value === 'string')`.","message":"The type used for unknown Cassandra types changed from `any` to `unknown`. This requires consumers of generated types to explicitly handle `unknown` where previously `any` might have been implicitly accepted, potentially leading to compilation errors.","severity":"breaking","affected_versions":">=0.0.10"},{"fix":"Update existing code that interacts with generated row types to account for optional and nullable properties. Ensure proper null checks or default assignments for these fields.","message":"Non-primary key properties in generated row types (for insert/retrieve contexts) are now marked as optional (`?`) and nullable (`| null`). This aligns with `cassandra-driver`'s behavior but changes the shape of generated interfaces.","severity":"breaking","affected_versions":">=0.0.9"},{"fix":"Always use `npm exec cassandra-codegen -- <args>` or `yarn cassandra-codegen <args>` to ensure the command is found and executed correctly within the project context.","message":"Executing the `cassandra-codegen` CLI directly might fail with 'command not found' if your npm configuration doesn't automatically add `node_modules/.bin` to your PATH.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"Ensure `await initMappers(yourCassandraClient);` is called early in your application's lifecycle, typically during your database connection initialization phase.","message":"The `initMappers` function must be called exactly once with a connected `cassandra-driver` client instance before any generated mappers can be used. Failure to do so will result in runtime errors.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"Upgrade to `cassandra-codegen@0.0.11` or newer to correctly handle Cassandra `map` types and ensure proper mapping to TypeScript `Record<string, any>` (or `Record<K, V>` if types are inferable).","message":"Prior to v0.0.11, there was a bug in the regex responsible for parsing the `map` type, potentially leading to incorrect type generation or errors when encountering Cassandra `map` types. Support for `map` type to TypeScript's `Record` was also limited before v0.0.10 unless `--use-js-map` was used.","severity":"gotcha","affected_versions":"<0.0.11"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Call `await initMappers(yourConnectedCassandraClient);` once at application startup.","cause":"The `initMappers` function was not called with a connected Cassandra client before attempting to use a generated mapper.","error":"ReferenceError: Cannot access 'cyclistCategoryMapper' before initialization"},{"fix":"Verify the `--host`, `--port`, `--datacenter`, `--username`, and `--password` arguments when running `cassandra-codegen`, and check your `cassandra-driver` client configuration. Ensure the Cassandra database is running and reachable from your application's environment.","cause":"The Cassandra host, port, datacenter, or credentials provided to the `cassandra-codegen` CLI or the `cassandra-driver` client are incorrect, or the Cassandra instance is not running/accessible.","error":"Error: All contact points failed to connect"},{"fix":"Upgrade `cassandra-codegen` to version 0.0.11 or newer. Re-run the code generation CLI tool to regenerate the types, ensuring the `map` type is correctly mapped to `Record<K, V>` in TypeScript.","cause":"This error can occur if your Cassandra table uses a `map` type column and you are using `cassandra-codegen` version older than 0.0.10/0.0.11, or the generated types are incorrect.","error":"Property 'mapColumn' does not exist on type 'CyclistCategoryRow'"}],"ecosystem":"npm","meta_description":null}