Skip to content

Add databaseTypes.ts file generation#16

Merged
absolutejs merged 4 commits intomainfrom
feat/add-database-types
Nov 24, 2025
Merged

Add databaseTypes.ts file generation#16
absolutejs merged 4 commits intomainfrom
feat/add-database-types

Conversation

@bnziv
Copy link
Copy Markdown
Collaborator

@bnziv bnziv commented Nov 24, 2025

Summary by CodeRabbit

  • New Features

    • Automatic generation of database TypeScript definitions during project scaffolding, saved to a dedicated types location for improved type safety.
    • Project initialization now exposes a dedicated types directory so generated types are placed alongside other project assets.
  • Chores

    • Imports and scaffolding flow updated to use the new types outputs where applicable.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 24, 2025

Walkthrough

Adds a dedicated database type generator and a new typesDirectory created at initialization, threads typesDirectory through scaffolding, moves database-host-specific type emissions out of the drizzle schema generator into generateDatabaseTypes, and updates import usage to reference the new types file for absoluteAuth.

Changes

Cohort / File(s) Change Summary
Initialization
src/generators/configurations/initializeRoot.ts
Adds typesDirectory constant (src/types), creates the directory, and appends typesDirectory to the returned initialization object.
Database type generator
src/generators/db/generateDatabaseTypes.ts
New file: exports GenerateTypesProps and generateDatabaseTypes; builds TypeScript type declaration strings conditionally from databaseHost and authProvider.
Schema generator
src/generators/db/generateDrizzleSchema.ts
Removes databaseHost from GenerateSchemaProps and function signature; deletes database-host-specific type export branches and removes DatabaseHost import.
Database scaffolding
src/generators/db/scaffoldDatabase.ts
Adds typesDirectory to ScaffoldDatabaseProps and function signature; calls generateDatabaseTypes(...) and writes typesDirectory/databaseTypes.ts; stops passing databaseHost into generateDrizzleSchema.
Top-level scaffolding
src/scaffold.ts
Destructures typesDirectory from initializeRoot result and forwards it to scaffoldDatabase.
Project imports
src/generators/project/generateImportsBlock.ts
When authProvider === 'absoluteAuth', imports schema from '../../db/schema' and User from '../types/databaseTypes' (previously both from '../../db/schema').

Sequence Diagram(s)

sequenceDiagram
    participant CLI as scaffold.ts
    participant Init as initializeRoot
    participant FS as File System
    participant ScDB as scaffoldDatabase
    participant GenSchema as generateDrizzleSchema
    participant GenTypes as generateDatabaseTypes

    CLI->>Init: initializeRoot(projectName, templatesDirectory)
    Init->>FS: create `src/types` (typesDirectory)
    Init-->>CLI: {backendDir, frontendDir, assetsDir, typesDir}

    CLI->>ScDB: scaffoldDatabase(..., typesDir)
    alt orm === "drizzle"
        ScDB->>GenSchema: generateDrizzleSchema({databaseEngine, authProvider})
        GenSchema-->>ScDB: schema string
        ScDB->>FS: write schema file

        ScDB->>GenTypes: generateDatabaseTypes({databaseHost, authProvider})
        GenTypes-->>ScDB: types string
        ScDB->>FS: write typesDir/databaseTypes.ts
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review points:
    • Ensure typesDirectory is correctly created and propagated from initializeRootscaffold.tsscaffoldDatabase.
    • Validate conditional assembly in generateDatabaseTypes for all databaseHost and authProvider combinations.
    • Confirm removal of databaseHost from generateDrizzleSchema does not leave missing types or imports.
    • Verify generateImportsBlock imports align with produced databaseTypes.ts exports and relative paths.

Possibly related PRs

  • Add MariaDB support #9 — Edits the same DB generator modules (notably generateDrizzleSchema and generateImportsBlock); relevant because both PRs change schema generation and import usage.

Poem

🐇 I hopped to src/types, a cozy little den,
I stitched the DB types, then hopped back again.
Drizzle now hums without host in its tune,
Imports point home beneath the moon.
A rabbit's small patch — type-springs in bloom.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately captures the main objective: adding a new databaseTypes.ts file generation feature. The title is directly supported by the substantial changes across multiple files that implement this functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-database-types

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf8e385 and 2c0bf94.

📒 Files selected for processing (5)
  • src/generators/configurations/initializeRoot.ts (2 hunks)
  • src/generators/db/generateDatabaseTypes.ts (1 hunks)
  • src/generators/db/generateDrizzleSchema.ts (1 hunks)
  • src/generators/db/scaffoldDatabase.ts (4 hunks)
  • src/scaffold.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/generators/db/scaffoldDatabase.ts (1)
src/generators/db/generateDatabaseTypes.ts (1)
  • generateDatabaseTypes (8-42)
src/generators/db/generateDatabaseTypes.ts (1)
src/types.ts (2)
  • DatabaseHost (49-49)
  • AuthProvider (40-40)
🔇 Additional comments (14)
src/generators/configurations/initializeRoot.ts (2)

17-18: LGTM!

The types directory creation follows the same pattern as other directories in this initialization function and is properly placed within the src directory structure.


44-49: LGTM!

The return object is correctly extended to include typesDirectory, maintaining backwards compatibility by preserving all existing fields.

src/scaffold.ts (2)

49-54: LGTM!

The destructuring correctly extracts the new typesDirectory field from initalizeRoot's return value.


110-111: LGTM!

The typesDirectory parameter is correctly passed to scaffoldDatabase, completing the propagation of the types directory path through the scaffolding pipeline.

src/generators/db/scaffoldDatabase.ts (4)

9-9: LGTM!

The import of generateDatabaseTypes is correctly added to support the new type generation functionality.


26-26: LGTM!

The typesDirectory parameter is correctly added to both the type definition and function signature, maintaining consistency with other directory parameters.

Also applies to: 36-37


91-94: LGTM!

The removal of databaseHost from generateDrizzleSchema is correct, as database-specific type generation has been decoupled and moved to generateDatabaseTypes.


101-105: I need to search the codebase directly for the type definitions and validation of databaseHost. Let me check the relevant files:

Based on my verification, I found that the original review comment flagged a legitimate concern about the generateDatabaseTypes function. The search results confirm that:

  1. generateDatabaseTypes in src/generators/db/generateDatabaseTypes.ts only explicitly handles three cases: 'neon', 'planetscale', and 'turso'
  2. There is no else clause or default case after line 24, which means if databaseHost is any other value (including 'none' or undefined), no DatabaseType export is generated
  3. The function is called with databaseHost parameter at line 101-105 in scaffoldDatabase.ts

However, I was unable to definitively verify:

  • Whether databaseHost can actually reach this code path with 'none' or undefined values in practice
  • Whether any code actually imports and uses the generated DatabaseType type
  • Whether upstream validation prevents invalid databaseHost values from reaching this function

The original issue is valid in principle—incomplete type generation for unhandled cases is a code quality concern—but the actual impact depends on runtime constraints and usage patterns that require manual verification.


Verify handling of unhandled databaseHost values in generateDatabaseTypes function.

The function at src/generators/db/generateDatabaseTypes.ts only handles three cases ('neon', 'planetscale', 'turso'). If databaseHost has any other value, the DatabaseType type export is omitted from the generated file. Confirm whether:

  • Code paths can reach this function with values other than the three handled cases
  • Whether any module imports the generated DatabaseType and would fail if missing
  • Whether upstream validation prevents invalid databaseHost values
src/generators/db/generateDatabaseTypes.ts (3)

1-6: LGTM!

The type definition and imports are appropriate for the function's requirements.


26-35: LGTM!

The conditional logic for authProvider correctly generates appropriate imports and type exports. The relative import path '../../db/schema' assumes the generated file will be at src/types/databaseTypes.ts with the schema at src/db/schema.ts, which aligns with the directory structure created by initializeRoot.


37-41: Template assembly is correct but depends on upstream validation.

The string template correctly assembles the type definitions. However, the conditional on Line 40 that adds extra newlines only when dbTypeLine exists means the generated file structure will differ based on whether a valid databaseHost was provided. This is related to the issue flagged in lines 12-24 regarding unhandled databaseHost values.

src/generators/db/generateDrizzleSchema.ts (3)

1-1: LGTM!

The removal of DatabaseHost from imports is correct, as this parameter is no longer used in schema generation.


54-64: LGTM!

The removal of databaseHost from the function signature is correct and represents a clean separation of concerns. Schema generation now focuses solely on table definitions, while database-specific type generation is handled separately by generateDatabaseTypes.


121-134: LGTM!

The schema export correctly provides the SchemaType that is consumed by generateDatabaseTypes to create type-safe database type definitions. The integration between schema generation and type generation is well-structured.

Comment on lines +12 to +24
let dbImport = '';
let dbTypeLine = '';
if (databaseHost === 'neon') {
dbImport = `import { NeonHttpDatabase } from 'drizzle-orm/neon-http';`;
dbTypeLine = 'export type DatabaseType = NeonHttpDatabase<SchemaType>;';
} else if (databaseHost === 'planetscale') {
dbImport = `import { PlanetScaleDatabase } from 'drizzle-orm/planetscale-serverless';`;
dbTypeLine =
'export type DatabaseType = PlanetScaleDatabase<SchemaType>;';
} else if (databaseHost === 'turso') {
dbImport = `import { LibSQLDatabase } from 'drizzle-orm/libsql';`;
dbTypeLine = 'export type DatabaseType = LibSQLDatabase<SchemaType>;';
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Add handling for unhandled databaseHost values.

The function only handles 'neon', 'planetscale', and 'turso' as databaseHost values, but according to the type definition, databaseHost can also be undefined or 'none'. When an unhandled value is provided, dbImport and dbTypeLine remain empty strings, resulting in a generated file without a DatabaseType export. This will cause TypeScript compilation errors if downstream code imports or references DatabaseType.

Consider one of the following approaches:

  1. Add validation to prevent calling this function with unsupported databaseHost values
  2. Add a default case that throws an error for unsupported values
  3. Return early or skip file generation for non-hosted database scenarios

Apply this diff to add validation:

 export const generateDatabaseTypes = ({
 	databaseHost,
 	authProvider
 }: GenerateTypesProps) => {
+	// Skip type generation for non-hosted databases
+	if (!databaseHost || databaseHost === 'none') {
+		return null;
+	}
+
 	let dbImport = '';
 	let dbTypeLine = '';
 	if (databaseHost === 'neon') {
 		dbImport = `import { NeonHttpDatabase } from 'drizzle-orm/neon-http';`;
 		dbTypeLine = 'export type DatabaseType = NeonHttpDatabase<SchemaType>;';
 	} else if (databaseHost === 'planetscale') {
 		dbImport = `import { PlanetScaleDatabase } from 'drizzle-orm/planetscale-serverless';`;
 		dbTypeLine =
 			'export type DatabaseType = PlanetScaleDatabase<SchemaType>;';
 	} else if (databaseHost === 'turso') {
 		dbImport = `import { LibSQLDatabase } from 'drizzle-orm/libsql';`;
 		dbTypeLine = 'export type DatabaseType = LibSQLDatabase<SchemaType>;';
+	} else {
+		throw new Error(`Unsupported databaseHost: ${databaseHost}`);
 	}

Then update the caller in scaffoldDatabase.ts to handle the null return:

const drizzleTypes = generateDatabaseTypes({
	authProvider,
	databaseHost
});
if (drizzleTypes !== null) {
	writeFileSync(join(typesDirectory, 'databaseTypes.ts'), drizzleTypes);
}

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c0bf94 and 13cf37f.

📒 Files selected for processing (1)
  • src/generators/project/generateImportsBlock.ts (1 hunks)

Comment on lines +162 to +164
...(authProvider === 'absoluteAuth'
? [`import { schema } from '../../db/schema'`, `import { User } from '../types/databaseTypes'`]
: [`import { schema } from '../../db/schema'`])
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot Nov 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the import path and User type availability.

The User type import has been moved from '../../db/schema' to '../types/databaseTypes'. Ensure that:

  1. The relative path '../types/databaseTypes' correctly resolves to the new typesDirectory location from the generated backend file
  2. The User type is properly exported from the generated databaseTypes.ts file

Run the following script to verify the import path and type availability:


🏁 Script executed:

#!/bin/bash
# Description: Verify the User type is exported from the new databaseTypes file and check path consistency

# Find where generateDatabaseTypes creates the types file
echo "=== Checking generateDatabaseTypes implementation ==="
ast-grep --pattern 'export $_ generateDatabaseTypes($$$) {
  $$$
}'

# Search for User type exports in database type generation
echo -e "\n=== Searching for User type exports ==="
rg -nP --type=ts 'export\s+(type|interface)\s+User\b' -C 3

# Check where the imports are being written relative to backend directory
echo -e "\n=== Checking typesDirectory usage in scaffolding ==="
rg -nP --type=ts 'typesDirectory' -C 2

# Verify the generated imports structure
echo -e "\n=== Checking other usages of schema imports ==="
rg -nP --type=ts "from ['\"].*db/schema['\"]" -C 1

Length of output: 5506


Fix relative import path for User type.

The User type is correctly exported from the generated databaseTypes.ts file, but the relative import path is incorrect. The path should be '../../types/databaseTypes' (not '../types/databaseTypes') to correctly resolve from the generated backend file location to src/types/databaseTypes.ts.

Update line 163 in src/generators/project/generateImportsBlock.ts:

? [`import { schema } from '../../db/schema'`, `import { User } from '../../types/databaseTypes'`]
🤖 Prompt for AI Agents
In src/generators/project/generateImportsBlock.ts around lines 162 to 164, the
relative import for the User type is wrong; change the second import path from
'../types/databaseTypes' to '../../types/databaseTypes' so the generated backend
file correctly resolves src/types/databaseTypes.ts. Update the array returned
when authProvider === 'absoluteAuth' to use `import { User } from
'../../types/databaseTypes'` while keeping the schema import as-is.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The path is correct as the import is in src/backend/server.ts and the types file is in src/types/databaseTypes.ts

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bnziv, you're absolutely right! I apologize for the confusion.

From src/backend/server.ts to src/types/databaseTypes.ts, the relative path '../types/databaseTypes' is indeed correct:

  • ../ goes up from backend/ to src/
  • types/databaseTypes then navigates into the types directory

The import path as written in the code is accurate. Thank you for the clarification!

@absolutejs absolutejs merged commit 41a0499 into main Nov 24, 2025
1 check passed
@absolutejs absolutejs deleted the feat/add-database-types branch November 24, 2025 06:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants