Generating migrations with cli

See original GitHub issue

Issue Description

Expected Behavior

Migrations get generated using the cli

Actual Behavior

I am following the documentation outlined here https://typeorm.io/migrations and I feel like the documentation is way different then what is actually happening in the cli. I have tried just running the following command:

typeorm migration:generate -n PostRefactoring

When I run this command I get the following:

Not enough non-option arguments: got 0, need at least 1

So then I modify the command to something like this:

Missing required argument: dataSource

So then from there I add the datasource since that is what it is asking for:

npx typeorm migration:generate test -d app-data-source.ts (I found the -d somewhere online while investigating this issue)

But once I run that command I get the following error:

File must contain a TypeScript / JavaScript code and export a DataSource instance.

I have been trying to get this to work for days and I am about ready to throw the towl in and use a different ORM…which I don’t want to do. I know that everything is working fine because I can start up the app and the app connects to the database and creates rows in the database. So it is just something with the cli and trying to generate the migrations.

Here is what is in my app-data-source.ts file:

import { DataSource } from "typeorm";
import { User } from "./entitiy/User";

const myDataSource = new DataSource({
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "",
  database: "postgres",
  entities: [User],
  migrations: ["/migrations/"],
  logging: true,
  synchronize: true,
});


export default myDataSource;

This is the contents of my app.ts file:

import * as express from "express";
import { Request, Response } from "express";
import myDataSource from "./app-data-source";
import { User } from "./entitiy/User";

// establish database connection
myDataSource
  .initialize()
  .then(() => {
    console.log("Data Source has been initialized!");
  })
  .catch((err) => {
    console.error("Error during Data Source initialization:", err);
  });

// create and setup express app
const app = express();
app.use(express.json());

// register routes
app.get("/users", async function (req: Request, res: Response) {
  const users = await myDataSource.getRepository(User).find();
  res.json(users);
});

app.get("/users/:id", async function (req: Request, res: Response) {
  const results = await myDataSource.getRepository(User).findOneBy({
    id: +req.params.id,
  });
  return res.send(results);
});

app.post("/users", async function (req: Request, res: Response) {
  const user = await myDataSource.getRepository(User).create(req.body);
  const results = await myDataSource.getRepository(User).save(user);
  return res.send(results);
});

app.put("/users/:id", async function (req: Request, res: Response) {
  const user = await myDataSource.getRepository(User).findOneBy({
    id: +req.params.id,
  });
  myDataSource.getRepository(User).merge(user, req.body);
  const results = await myDataSource.getRepository(User).save(user);
  return res.send(results);
});

app.delete("/users/:id", async function (req: Request, res: Response) {
  const results = await myDataSource.getRepository(User).delete(req.params.id);
  return res.send(results);
});

// start express server
app.listen(3000);

All these files were setup using the instructions outlined in the express typeorm documentation: Example with Express

Which BTW, this also has issues and doesn’t run from what is outlined in the directions. I had to make some modifications to actually make the app run compared to what is outlined in that guide. One of the changes I made in the data source file was putting the actual Entity name in the entity property of the datasource compared to the guide that has you put the path in.

Anyway, am I crazy…am I doing something wrong? You guys might not have enough information to answer the first question but can you at least help with trying to figure out how to make the migrations work?

Steps to Reproduce

Set up you app using the guide outlined above to use express

My Environment

Dependency Version
Operating System MAC OS Monterrey
Node.js version v16.14.2
Typescript version 4.5.2
TypeORM version 0.3.4

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres yes
react-native no
sap no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, and I know how to start.
  • ✖️ Yes, I have the time, but I don’t know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✅ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:28
  • Comments:38 (1 by maintainers)

github_iconTop GitHub Comments

116reactions
matthewdownscommented, Mar 28, 2022

How did 0.3.0 get past the testing phase when the CLI is completely broken?

65reactions
thenaimcommented, Jun 23, 2022

TypeScript/Nestjs

ormconfig.ts:

import * as dotenv from 'dotenv';
import { cwd, env } from 'process';
import { DataSource } from 'typeorm';

dotenv.config();

export const dataSource = new DataSource({
  type: 'postgres',
  host: env.TYPEORM_HOST,
  port: parseInt(env.TYPEORM_PORT),
  username: env.TYPEORM_USER,
  password: env.TYPEORM_PASSWORD,
  database: env.TYPEORM_DB,
  entities: [cwd() + '/src/**/*.entity.ts'],
  migrations: [cwd() + '/src/migrations/*.ts'],
  migrationsTableName: 'migrations',
  synchronize: false,
  dropSchema: false,
});

package.json:

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ./src/config/ormconfig.ts",
"migration:create": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli migration:create ./src/migrations/$npm_config_name",
"migration:generate": "npm run typeorm -- migration:generate ./src/migrations/$npm_config_name",
"migration:run": "npm run typeorm -- migration:run",
"migration:revert": "npm run typeorm -- migration:revert",
"schema:sync": "npm run typeorm -- schema:sync"

command to create/generate a migration.

npm run migration:create --name=foo
npm run migration:generate --name=bar
Read more comments on GitHub >

github_iconTop Results From Across the Web

Migrations Overview - EF Core | Microsoft Learn
You're now ready to add your first migration! Instruct EF Core to create a migration named InitialCreate: .NET Core CLI; Visual Studio.
Read more >
Migration in Entity Framework Core
EF Core migrations are a set of commands which you can execute in NuGet Package Manager Console or in dotnet Command Line Interface...
Read more >
How to auto generate migrations with Sequelize CLI from ...
If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:.
Read more >
Migrations | Sequelize
Migrations · Installing the CLI​ · Project bootstrapping​ · Creating the first Model (and Migration)​ · Running Migrations​ · Undoing Migrations​.
Read more >
Using CLI - typeorm - GitBook
Generate a migration from existing table schema ... Automatic migration generation creates a new migration file and writes all sql queries that must...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found