Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

0.3.0: Connection "default" was not found for creating entities with dataSource #8758

Closed
Q16solver opened this issue Mar 17, 2022 · 16 comments
Closed
Labels

Comments

@Q16solver
Copy link
Contributor

Q16solver commented Mar 17, 2022

Issue Description

The datasource I'm using:

export const dataSource = new DataSource({
  type: "postgres",
  url: process.env.DATABASE_URL,
  migrations: [path.join(__dirname, "./migrations/*")],
  entities: [path.join(__dirname, "./entities/*")],
  subscribers: [path.join(__dirname, "./subscribers/*")],
  logging: !__prod__,
  migrationsRun: true,
  synchronize: true,
});

and for a Post entity if I do

dataSource.getRepository(Post).create({...someEntity}).save() (or getTreeRepository)

This will complain that there is no default connection, it does not happen for the other basic methods insert, update, delete etc, I think it will have this problem for other methods like remove though, which aren't sql methods

Expected Behavior

The post should be created and saved properly along with its tree parent/children if it exists, like in 0.2.x versions

Actual Behavior

Connection "default" was not found

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. 5$
  • ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.
@Q16solver Q16solver changed the title 0.3.0: Connection "default" was not found 0.3.0: Connection "default" was not found for creating entities with dataSource Mar 17, 2022
@pleerock
Copy link
Member

Did you call dataSource.initialize() before using repositories ?

@Q16solver
Copy link
Contributor Author

Q16solver commented Mar 18, 2022

Yep, I've checked that things work with insert, update and delete methods already, so that should also be the case that I need to initialize before those methods work

@Q16solver
Copy link
Contributor Author

Q16solver commented Mar 18, 2022

I've had quick look at the code, and the insert method for example uses this.createQueryBuilder, whereas the create method uses this.connection etc, which might be the problem it tries to find a default connection. With the old connection API, it sets the default connection to be the first datasource we use I believe, do we have a similar option here for new DataSource(..)?

@pleerock
Copy link
Member

can you provide the whole stack trace in order to understand where exactly this error comes from

@pleerock
Copy link
Member

do you have entities extending BaseEntity ?

@Q16solver
Copy link
Contributor Author

ConnectionNotFoundError: Connection "default" was not found.
    at ConnectionManager.get (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/connection/ConnectionManager.ts:43:32)
    at getConnection (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/globals.ts:132:35)
    at Function.getRepository (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/repository/BaseEntity.ts:108:58)
    at Post.save (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/repository/BaseEntity.ts:52:42)
    at PostResolver.<anonymous> (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/resolvers/post.ts:132:85)
    at Generator.next (<anonymous>)
    at /Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/resolvers/post.ts:20:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/resolvers/post.ts:16:12)
    at PostResolver.createPost (/Users/jimmychen/Desktop/Actually_Uni/Programmin/Software/React/Demos/Esposter-backend/src/resolvers/post.ts:84:16)

Yep

import { Updoot } from "@entities/Updoot";
import { User } from "@entities/User";
import { Field, Int, ObjectType } from "type-graphql";
import {
  BaseEntity,
  Column,
  CreateDateColumn,
  Entity,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  Tree,
  TreeChildren,
  TreeParent,
  UpdateDateColumn,
} from "typeorm";

@ObjectType()
@Entity()
@Tree("closure-table")
export class Post extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Field({ nullable: true })
  @Column({ nullable: true })
  parentId?: string;

  @TreeParent()
  parent: Post;

  @Field(() => Int)
  @Column({ default: 1 })
  level: number;

  @Field(() => [Post], { nullable: true })
  @TreeChildren()
  children: Post[] | null;

  @Field()
  @Column({ default: "" })
  title: string;

  @Field()
  @Column({ default: "" })
  text: string;

  @Field({ nullable: true })
  @Column({ nullable: true })
  gifId?: string;

  @Field(() => Int)
  @Column({ default: 0 })
  points: number;

  @Field(() => Int)
  @Column({ default: 0 })
  commentsCount: number;

  @Field()
  @Column({ type: "double precision" })
  ranking: number;

  @Field()
  @Column({ default: false })
  edited: boolean;

  @Field(() => Int, { nullable: true })
  voteStatus: number | null; // 1 or -1 or null

  @Field()
  @Column()
  creatorId: string;

  /* Post structure is more complicated so we cannot just set onDelete: "CASCADE"
  when deleting the user and will have to manually delete ourselves :C */
  @Field(() => User)
  @ManyToOne(() => User, (user) => user.posts)
  creator: User;

  @OneToMany(() => Updoot, (updoot) => updoot.post)
  updoots: Updoot[];

  @Field()
  @CreateDateColumn()
  createdAt: Date;

  @Field()
  @UpdateDateColumn()
  updatedAt: Date;
}

@pleerock
Copy link
Member

okay I think I know what is the problem. For now you need to set YourEntity.useConnection(dataSource) for each entity you have as a hotfix. I'll push a PR for this issue.

@pleerock
Copy link
Member

fixed by #8764

@Q16solver
Copy link
Contributor Author

@pleerock Confirmed that fix seems to have worked in 0.3.1! Donated 👍 . However, currently also experiencing issue #8768 , as the code in this issue also uses glob paths

@huangyingjie
Copy link

Problem still exists in v0.3.10. I init my project by typeorm, did't change any code except db user/password

import { getRepository } from "typeorm"
import { NextFunction, Request, Response } from "express"
import { User } from "../entity/User"

export class UserController {

    private userRepository = getRepository(User)

    async all(request: Request, response: Response, next: NextFunction) {
        return this.userRepository.find()
    }

  ......

ConnectionNotFoundError: Connection "default" was not found.
at ConnectionManager.get ....

@tirathsharma098
Copy link

tirathsharma098 commented Nov 22, 2022

Screenshot from 2022-11-22 20-41-51

okay I think I know what is the problem. For now you need to set YourEntity.useConnection(dataSource) for each entity you have as a hotfix. I'll push a PR for this issue.

I am using 0.3.10 still facing same issue.

@greenreign
Copy link

greenreign commented Dec 14, 2022

This is still a problem in 0.3.11. @pleerock Can you advise? When using some methods everything is fine. When using the deprecated getRepository I see this error. I tried changing it to datasource.getRepository and receive the same error.

 ConnectionNotFoundError: Connection "default" was not found.

It may be only when using queryBuilder. I'm still trying to narrow it down.
I'm trying to upgrade from 0.2.40 to 0.3.11. I also found that the deprecated findByIds stopped returning relations so I had to switch to the new findBy.

@greenreign
Copy link

greenreign commented Dec 14, 2022

I updated my comment above to strike out what eventually worked. To recap...
In typeorm@0.3.11 if using getRepository I will get this stack

ConnectionNotFoundError: Connection "default" was not found.
              at ConnectionManager.get (C:\Users\sesti\coast\core-api\node_modules\typeorm\connection\ConnectionManager.js:43:19)
              at getRepository (C:\Users\sesti\coast\core-api\node_modules\typeorm\globals.js:133:10)

This is a bug. The method is deprecated but should still work. All other approaches to access data work fine before and after this call. The datasource is confirmed to be initiated and connections generally work but getRepository does not

However, if I access a repository in the new, prescribed method through datasource this does fix my problem

datasource.getRepository ✔️

@philipp-schmidt
Copy link

I can confirm this issue still exists in 0.3.17

What is the accepted way of declaring a DataSource and also using BaseEntity (ActiveRecord pattern)?

I always get ConnectionNotFoundError: Connection "default" was not found.

Trying to migrate from typeorm 0.2.20 to 0.3.17 and can not figure out how to migrate the code base from ConnectionOptions to DataSource.

Anybody already been through the process?

@philipp-schmidt
Copy link

I have tried to set ".useDataSource(...)" on each of my Entities, but I'm still getting the same error.

@guilhermeSDB
Copy link

I was having this problem when using

@InjectEntityManager()
private readonly entityManager: EntityManager

this.entityManager.getRepository(User)

So I switched to

@InjectDataSource()
public readonly dataSource: DataSource;

this.dataSource.getRepository(User)

And I created a module called DatabaseModule

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.getOrThrow('TYPEORM_HOST'),
        port: configService.getOrThrow('TYPEORM_PORT'),
        username: configService.getOrThrow('TYPEORM_USERNAME'),
        password: configService.getOrThrow('TYPEORM_PASSWORD'),
        database: configService.getOrThrow('TYPEORM_DATABASE'),
        logging: configService.getOrThrow('TYPEORM_LOGGING'),
        synchronize: false,
        autoLoadEntities: true
      }),
      inject: [ConfigService],
    }),
  ],
})
export class DatabaseModule {}

my app.module

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    AuthModule,
    MailerModule,
    ModelsModule,
    SharedModule,
    DatabaseModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

This worked perfectly for me replacing the deprecated getRepository(), and apparently it works well inside entities too, this has been my solution so far

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants