Git Product home page Git Product logo

typeorm-naming-strategies's Introduction

Typeorm naming strategies

This package provides a few (one, at the moment) useful custom naming strategies. It alterates the name of columns, relations and other fields in database.

For example, using the snake strategy, if you have a model like this:

class User {
  @Column()
  createdAt;
}

In the DB the createdAt field will be created_at

Naming strategies available

  • Snake

Installation

It's available as an npm package

npm install typeorm-naming-strategies --save

Or using yarn

yarn add typeorm-naming-strategies

Usage

import { createConnection } from 'typeorm';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';

await createConnection({
  ...
  namingStrategy: new SnakeNamingStrategy(), // Here you'r using the strategy!
});

Alternatively you can use it in combination with a ormconfig.js

// Use require instead of import
const SnakeNamingStrategy = require("typeorm-naming-strategies").SnakeNamingStrategy

module.exports = {
  ...
  namingStrategy: new SnakeNamingStrategy(),
}

typeorm-naming-strategies's People

Contributors

andryuha49 avatar davewelsh avatar kevinnovak avatar luisignaciocc avatar nebkat avatar sanderlissenburg avatar sophiabits avatar tonivj5 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

typeorm-naming-strategies's Issues

TypeORM module resolution issue after 0.2.42

TypeORM has recently released the 0.2.42 version and added an exports field into package.json.

The snake-naming.strategy.js file currently imports the typeorm/util/StringUtils module from the typeorm package, which conflicts with the new package.json exports field.

Error: Cannot find module '/var/app/current/node_modules/typeorm/util/StringUtils'
   ...
  code: 'MODULE_NOT_FOUND',
  path: '/var/app/current/node_modules/typeorm/package.json'
}

Using `JoinTable` with `name` causes SQLITE_ERROR

Using an entity with a ManyToMany relationship structured like this:

  @ManyToMany(() => Company)
  @JoinTable({name: "companies_wishlist"})
  @Expose({ name: "wishlist_companies" })
  wishlistCompanies: Company[];

causes (with logging turned on to see the faulty query):

query: CREATE TABLE "temporary_users_companies_wishlist" ()
query failed: CREATE TABLE "temporary_users_companies_wishlist" ()
error: Error: SQLITE_ERROR: near ")": syntax error
--> in Database#all('CREATE TABLE "temporary_users_companies_wishlist" ()', undefined, [Function: handler])
    at execute (C:\Users\pwd06\git\buddee-back-end\src\driver\sqlite\SqliteQueryRunner.ts:77:46)
    at C:\Users\pwd06\git\buddee-back-end\src\driver\sqlite\SqliteQueryRunner.ts:137:19 {
  errno: 1,
  code: 'SQLITE_ERROR',
  __augmented: true
}
query: ROLLBACK

Removing name, or disabling snake case naming, fixes the problem

How to avoid naming change ?

I have a table called order_info and it has a column commodityid.
But i do not know why it has been changed to commodity_id when searching.

sqlMessage: "Unknown column 'order_info.commodity_id' in 'field list'",

Duplicate underscore in oneToMany

Using an entity with a column like this:

  @ManyToOne(() => Degree, { nullable: true })
  @JoinColumn()
  parentDegree?: Degree;

yields the column name parent_degree__id instead of parent_degree_id

problem with StringUtils

Hi there! I have a typescript project with
typeorm 0.2.44 and typeorm-naming-strategies 3.0.0

this is what I see on startup

node:internal/modules/cjs/loader:488
      throw e;
      ^

Error: Cannot find module '~/node_modules/typeorm/util/StringUtils.js.js'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:94:18)
    at Object.<anonymous> (~/node_modules/typeorm-naming-strategies/snake-naming.strategy.js:5:26)
    at Module._compile (node:internal/modules/cjs/loader:1101:14) {
  code: 'MODULE_NOT_FOUND',
  path: '~/node_modules/typeorm/package.json'
}

I believe this is related to typescript config but I have to idea how it should look like for this to work

Naming strategy doesn't applied to query builder return value

I've recently found out that naming strategy doesn't applied perfectly when I use it with query builder.
More precisely, it works when I write queries, but it doesn't work with the returned value by the query builder.
I'll attach my example below.

image

image

I think if I don't specify aliases with 'as', keys might be ambiguous if I join extra tables, so it might return snake case names.
But I hope camel cases are returned when I specify their aliases.
In my example, user_manner_point to userMannerPoint, or userispro to userIsPro.

Did I miss something or does this package not support this currently?

Potential Duplicate Package Name

Hi, I'm not sure you're aware of this but it looks like 13 days ago someone pretty much copied your project and posted a near duplicate name of your package on packagist. I was confused by which one was the one I needed until I dug in and saw your project has been around for 3 years and the other one 13 days. I only saw a 1 line difference in snake-naming.strategy.ts file with no attribution to your project. Here is the link: https://www.npmjs.com/package/typeorm-naming-strategy

Just thought you'd like to be aware of this, It got me a bit paranoid due to all of the supply chain attacks going on.

Foreign key naming

I think it is not useful to automatically attach the referenced column name for FK column names, because it generates inconsistency of the property names and makes ist more difficult to find(out) the correct column name when referencing e.g. in where clause.
Example: FK property ofUserId would currently be renamed to of_user_id_user_id
and in my code I need to reference on this renaming

.where('user.of_user_id_user_id = :userId', { userId: userId })

Better:

.where('user.of_user_id = :user_id', { userId: userId })

TypeORM in general is here a litte bit unhandy in my opinion, because column names need to be hardcoded and this is really not useful when working with naming strategies. A simple workaround could be to provide a function that returns the correct column name, like col(User.userId), which can consider active naming strategies and for e.g. SnakeCase return user.user_id or user.userId for default config. But this way, the code is a lot easier to refactor.

Nice to have:

.where(col(User.userId) + '= :userId', { userId: userId })
// or
.where(col(User.userId), { userId: userId })

Is this project maintained?

I am considering using this library in my project, but I am warned by old issues and PRs not addressed at all. As an alternative, I can write my strategy, but reinventing the wheel is not what I prefer :)

Typeorm v0.3.3 support

The package.json file has already been updated to support v0.3.3 of typeorm, but no release has been created.

When will the realease be made, with the updated dependencies?

Thanks ๐Ÿ˜„

Alias replacement not taking account multiple lines

I'm using snake case, when using multiple lines ``, sometimes the column/table alias do not get replaced.

The first myModel.studentId, just before the or, do not get replaced in this example

this will not work

.innerJoin(MyModel, 'myModel', 'myModel.foreignId = another.foreignId')
.leftJoin(
  Message,
  'msg',
  `
  msg.receiverType = :userType and msg.receiverId = :userId and
  msg.senderType = 'Something' and msg.senderId = myModel.studentId
  or
  msg.receiverType = 'Something' and msg.receiverId = myModel.studentId and
  msg.senderType = :userType and msg.senderId = :userId
`
)

this one will

.innerJoin(MyModel, 'myModel', 'myModel.foreignId = another.foreignId')
.leftJoin(
  Message,
  'msg',
  `
  msg.receiverType = :userType and msg.receiverId = :userId and
  msg.senderType = 'Something' and msg.senderId = myModel.studentId or
  msg.receiverType = 'Something' and msg.receiverId = myModel.studentId and
  msg.senderType = :userType and msg.senderId = :userId
`
)

using .replace(/\s+/g, ' ') will also work

MongoDB integration

Hi!

There are MongoDB specific instructions for this package? It works like a charm in my Postgres database, but it simply won't work with MongoDB.

TypeError: namingStrategy.tableName is not a function

If I upgrade TypeORM from 0.2.22 to 0.2.26 or 0.2.27 I get the following error:

[Nest] 8223   - 09/29/2020, 10:55:02 AM   [ExceptionHandler] Unable to connect to the database. Retrying (1)... +2531ms
TypeError: namingStrategy.tableName is not a function
    at EntityMetadata.build (/Users/paul/code/my-project/node_modules/typeorm/metadata/EntityMetadata.js:492:58)
    at /Users/paul/code/my-project/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:67:72
    at Array.forEach (<anonymous>)
    at EntityMetadataBuilder.build (/Users/paul/code/my-project/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:67:14)
    at ConnectionMetadataBuilder.buildEntityMetadatas (/Users/paul/code/my-project/node_modules/typeorm/connection/ConnectionMetadataBuilder.js:58:141)
    at Connection.buildMetadatas (/Users/paul/code/my-project/node_modules/typeorm/connection/Connection.js:515:57)
    at Connection.<anonymous> (/Users/paul/code/my-project/node_modules/typeorm/connection/Connection.js:128:30)
    at step (/Users/paul/code/my-project/node_modules/tslib/tslib.js:141:27)
    at Object.next (/Users/paul/code/my-project/node_modules/tslib/tslib.js:122:57)
    at fulfilled (/Users/paul/code/my-project/node_modules/tslib/tslib.js:112:62)

... any idea what could be the problem?

Naming Strategy and Migration Files

Hello,

Thanks for making typeorm-naming-strategies!

I'd like to report something that I identified.
If we generate a migration file, the columns are not in snake case format.
For the moment, I didn't spend time to investigate more about this but I wanted to report this as a first step.

Steps:

  1. Run typeorm migration:generate -n MyMigrationFile
  2. Open the generated file. Typeorm doesn't convert in Snake case. Expecting created_atinstead of createdAt:
import { MigrationInterface, QueryRunner } from 'typeorm';

export class MyMigrationFile1596812506458 implements MigrationInterface {
  name = 'MyMigrationFile1596812506458'

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query("ALTER TABLE `my_entity` ADD `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)");
  }

  public async down(queryRunner: QueryRunner): Promise<void> {}
}

Entity sample (test.entity.ts):

import { Entity, PrimaryGeneratedColumn, CreateDateColumn } from 'typeorm';

@Entity()
export class MyEntity {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @CreateDateColumn()
  createdAt: Date;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.