A powerful CLI utility that automatically generates StepZen GraphQL schemas from Microsoft SQL Server databases. Connect to your MSSQL database, introspect the schema, and generate production-ready GraphQL types, queries, and StepZen configuration files with automatic foreign key relationship handling.
- 🔌 Easy Database Connection - Connect to MSSQL with simple configuration
- 🔍 Automatic Schema Introspection - Discovers tables, columns, types, and relationships
- 🎯 Smart Type Mapping - Converts SQL Server types to appropriate GraphQL types
- 🔗 Foreign Key Relationships - Automatically generates @materializer directives for related data
- 📝 StepZen Integration - Generates ready-to-use StepZen schemas with @dbquery directives
- 🎨 Flexible Configuration - YAML config files or environment variables
- 🚀 Multiple Modes - Interactive, CLI, or config-file driven
- 🔐 Secure - Environment variable support for sensitive credentials
- 🎛️ Table Filtering - Include specific tables with schema-qualified patterns
- 📦 Batch Processing - Process multiple tables efficiently
# Clone the repository
git clone <repository-url>cd mssqlgen
# Install dependencies
npm install
# Build the project
npm run build
# Link for global usage (optional)
npm linkmssqlgen initThis creates a mssqlgen.config.yaml file in your current directory.
Edit mssqlgen.config.yaml:
database:
server: localhostdatabase: mydbuser: sapassword: ${DB_PASSWORD}port: 1433options:
encrypt: truetrustServerCertificate: truegeneration:
outputDir: ./stepzentables:
- "dbo.*"# Include all tables in dbo schema
- "Sales.Customer"# Include specific table
- "Sales.Order*"# Include tables matching patternCreate a .env file:
DB_PASSWORD=your_secure_passwordmssqlgen testmssqlgen list-schemasmssqlgen generate# Using config file
mssqlgen generate --config mssqlgen.config.yaml
# Using CLI options
mssqlgen generate \
--server localhost \
--database mydb \
--user sa \
--password mypassword \
--output ./stepzen
# Generate specific tables only
mssqlgen generate --tables "Sales.*,dbo.Customer"# Dry run (preview without writing files)
mssqlgen generate --dry-run# Create default config
mssqlgen init
# Create config at custom path
mssqlgen init --output my-config.yaml# Test using config file
mssqlgen test# Test using specific config
mssqlgen test --config my-config.yaml# List all tables
mssqlgen list
# List using specific config
mssqlgen list --config my-config.yaml# List all schemas in the database
mssqlgen list-schemas
# List using specific config
mssqlgen list-schemas --config my-config.yamlmssqlgen interactive
# or
mssqlgen iPrompts you for all configuration options interactively.
database:
server: localhost # Database server addressdatabase: mydb # Database nameuser: sa # Database userpassword: ${DB_PASSWORD} # Password (use env var)port: 1433# Port (optional, default: 1433)options:
encrypt: true # Enable encryptiontrustServerCertificate: true # Trust self-signed certsconnectionTimeout: 30000# Connection timeout (ms)requestTimeout: 30000# Request timeout (ms)generation:
outputDir: ./stepzen # Output directory# Table filtering with schema-qualified patternstables:
- "dbo.*"# All tables in dbo schema
- "Sales.*"# All tables in Sales schema
- "*.Customer"# Customer table in any schema
- "Sales.Order*"# Tables starting with Order in Sales schema
- "Application.People"# Specific table# Feature flagsautoIncludeForeignKeyTables: true # Auto-include FK referenced tablesnaming:
typePrefix: ""# Prefix for type namestypeSuffix: ""# Suffix for type namesfieldCase: camelCase # Field naming: camelCase, snake_case, PascalCasefeatures:
generateMutations: true # Generate mutations (future)generateRelationships: true # Generate relationships with @materializerincludePagination: false # Include pagination (future)The tables array supports schema-qualified patterns:
"dbo.*"- All tables in thedboschema"Sales.*"- All tables in theSalesschema"*.Customer"- Table namedCustomerin any schema"Sales.Order*"- Tables starting withOrderinSalesschema"Application.People"- Specific table with schema
Auto-Include Foreign Key Tables:
When autoIncludeForeignKeyTables: true, the generator automatically includes tables that are referenced by foreign keys, even if they don't match your table patterns. This ensures complete relationship graphs.
# Database ConnectionDB_SERVER=localhostDB_DATABASE=mydbDB_USER=saDB_PASSWORD=your_passwordDB_PORT=1433# Connection OptionsDB_ENCRYPT=trueDB_TRUST_SERVER_CERTIFICATE=true# Generation OptionsOUTPUT_DIR=./stepzenGENERATE_MUTATIONS=trueGENERATE_RELATIONSHIPS=trueThe tool generates a complete StepZen schema structure:
stepzen/
├── config.yaml # StepZen configuration
├── index.graphql # Main schema index
└── types/
├── customer.graphql # Customer type and queries
├── order.graphql # Order type and queries
└── product.graphql # Product type and queries
types/customer.graphql:
typeCustomer {
customerId: Int!firstName: String!lastName: String!email: StringcreatedAt: String!orders: [Order]
@materializer(
query: "ordersByCustomerId"arguments: [{ name: "customerId", field: "customerId" }]
)
}
typeQuery {
customers: [Customer]
@dbquery(
type: "mssql"query: """ SELECT * FROM dbo.Customer"""configuration: "mssql_config"
)
customer(customerId: Int!): Customer@dbquery(
type: "mssql"query: """ SELECT * FROM dbo.Customer WHERE CustomerId = ?"""configuration: "mssql_config"
)
}types/order.graphql:
typeOrder {
orderId: Int!customerId: Int!orderDate: String!totalAmount: Floatcustomer: Customer@materializer(
query: "customer"arguments: [{ name: "customerId", field: "customerId" }]
)
}
typeQuery {
orders: [Order]
@dbquery(
type: "mssql"query: """ SELECT * FROM dbo.Order"""configuration: "mssql_config"
)
order(orderId: Int!): Order@dbquery(
type: "mssql"query: """ SELECT * FROM dbo.Order WHERE OrderId = ?"""configuration: "mssql_config"
)
ordersByCustomerId(customerId: Int!): [Order]
@dbquery(
type: "mssql"query: """ SELECT * FROM dbo.Order WHERE CustomerId = ?"""configuration: "mssql_config"
)
}The generator automatically detects foreign key relationships and creates:
- @materializer directives - Links related types together
- Relationship queries - Queries to fetch related data (e.g.,
ordersByCustomerId) - Bidirectional relationships - Both parent-to-child and child-to-parent
When a foreign key is detected (e.g., Order.CustomerId → Customer.CustomerId):
Child Type (
Order) gets a field pointing to parent:customer: Customer@materializer( query: "customer"arguments: [{ name: "customerId", field: "customerId" }] )
Parent Type (
Customer) gets a field for children:orders: [Order] @materializer( query: "ordersByCustomerId"arguments: [{ name: "customerId", field: "customerId" }] )
Relationship Query is generated:
ordersByCustomerId(customerId: Int!): [Order] @dbquery( type: "mssql"query: "SELECT * FROM dbo.Order WHERE CustomerId = ?"configuration: "mssql_config" )
- Automatic Graph Traversal - Navigate relationships naturally in GraphQL
- Efficient Queries - StepZen handles the data fetching
- Type Safety - Relationships are strongly typed
- No Manual Configuration - Everything is generated from database metadata
| SQL Server Type | GraphQL Type | Notes |
|---|---|---|
| INT, BIGINT, SMALLINT, TINYINT | Int | |
| DECIMAL, NUMERIC, MONEY, FLOAT | Float | |
| VARCHAR, NVARCHAR, CHAR, TEXT | String | |
| BIT | Boolean | |
| DATE, DATETIME, DATETIME2 | String | ISO 8601 format |
| UNIQUEIDENTIFIER | ID | UUID format |
| VARBINARY, BINARY | String | Base64 encoded |
# Install dependencies
npm install
# Run in development mode
npm run dev -- generate --config examples/mssqlgen.config.yaml
# Build
npm run build
# Run tests (when available)
npm test# Lint
npm run lint
# Format code
npm run format# Generate schema for entire database
mssqlgen generate
# Generate for specific schemas
mssqlgen generate --tables "Sales.*,Application.*"# Generate specific tables
mssqlgen generate --tables "dbo.Customer,dbo.Order"# Preview without writing files
mssqlgen generate --dry-run# Start MSSQL in Docker
docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=YourStrong@Passw0rd" \
-p 1433:1433 --name mssql \
-d mcr.microsoft.com/mssql/server:2019-latest
# Generate schema
mssqlgen generate \
--server localhost \
--database master \
--user sa \
--password "YourStrong@Passw0rd"# .github/workflows/generate-schema.ymlname: Generate GraphQL Schemaon:
push:
branches: [main]jobs:
generate:
runs-on: ubuntu-lateststeps:
- uses: actions/checkout@v2
- name: Setup Node.jsuses: actions/setup-node@v2with:
node-version: '16'
- name: Install dependenciesrun: npm install
- name: Generate schemaenv:
DB_PASSWORD: ${{ secrets.DB_PASSWORD }}run: npm run build && node dist/cli.js generate
- name: Commit generated schemarun: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add stepzen/ git commit -m "Update generated schema" || exit 0 git pushProblem: Cannot connect to database
Solutions:
- Verify server address and port
- Check firewall settings
- Enable TCP/IP in SQL Server Configuration Manager
- Try
trustServerCertificate: truefor self-signed certificates
Problem: Login failed for user
Solutions:
- Verify username and password
- Check SQL Server authentication mode (mixed mode required)
- Ensure user has appropriate permissions
Problem: No tables found
Solutions:
- Check table patterns in configuration (use schema-qualified patterns like "dbo.*")
- Verify user has permissions to read schema
- Ensure you're connecting to the correct database
- Use
list-schemascommand to see available schemas
- Database connection
- Schema introspection
- Basic type generation
- Query generation
- CLI interface
- Foreign key relationships
- @materializer directives
- Schema-qualified table filtering
- Auto-include FK referenced tables
- View support
- Custom naming conventions
- Mutation generation
- Stored procedure mapping
- Pagination support
- Custom scalars
- Schema validation
Contributions are welcome! Please feel free to submit a Pull Request.
MIT
For issues and questions, please open an issue on GitHub.