Git Product home page Git Product logo

Comments (7)

tonivj5 avatar tonivj5 commented on May 30, 2024

Hi @btxtiger, using the query builder you do not need to write the name of the column like it's in the database, you can put it as it's declared in your class.

For example, if your User class has a property ofUser (I'm supposing how it's your implementation):

class User {
    @PrimaryGeneratedColumn()
    id: number
    @OneToOne(() => User)
    @JoinColumn()
    ofUser: User
}

typeorm generates an of_user_id FK (if your PR is userId, it would be more verbose, of_user_user_id), but in any case, you should not worry about the column name in your db, because you can use the property name to do the query instead of the column name generated 🔥:

const user = await userRepository.createQueryBuilder('user')
                             .where('user.ofUser = :userId', {userId: 1}).getOne();

I think that's your problem, if I'm misunderstanding you, I'm sorry! 😆

from typeorm-naming-strategies.

btxtiger avatar btxtiger commented on May 30, 2024

using the query builder you do not need to write the name of the column like it's in the database, you can put it as it's declared in your class.

Indeed, there was another mistake which prevented it from working. Thanks for explanation!

typeorm generates an of_user_id FK (if your PR is userId, it would be more verbose, of_user_user_id), but in any case, you should not worry about the column name in your db, because you can use the property name to do the query instead of the column name generated

Thats correct, but if you need to use .getRawMany and .getRawOne because of using for example subselects with generated columns, you would get a diverging name as property for foreign key columns. It also deprives a bit the control of the programmer, because just using an ORM does not always mean "I don't want do handle the database by myself", especially when using a custom naming strategy. Otherwise i could just use the default settings.

Currently I wrote a cleanup method to get usable data from the .getRaw methods.
E.g. message_last_modified -> lastModified, as it would be without naming strategy.
It just camelCases all properties and optionally removes any table prefixes. If you might find that useful for adding to the snake naming strategy class, I could open a pull request for that.

public static cleanupGetRaw(rawData: RawDataObject | Array<RawDataObject>, deletePrefixes: Array<string> = []): any

from typeorm-naming-strategies.

tonivj5 avatar tonivj5 commented on May 30, 2024

I think it's interesting, however I have not that problem. How would its use? Can you show me an example?

const data = SnakeNamingStrategy.cleanupGetRaw(await db.builder(...).getRaw()); // Is it?

from typeorm-naming-strategies.

btxtiger avatar btxtiger commented on May 30, 2024

Actually thats all:

let data = await getRepository(User).(...).getRawMany();
/*
{
   user_id: 12,
   user_full_name: "Peter Shaw",
   userProfile_picture_url: "http:// ...."
}
*/

data = SnakeNamingStrategy.cleanupGetRaw(data, ['user', 'userProfile']);
/*
   id: 12,
   fullName: "Peter",
   pictureUrl: "http://"
*/
import { camelCase, snakeCase } from 'typeorm/util/StringUtils';

interface RawData {
   [key: string]: any;
}

/**
    * Cleanup response objects from .getRawMany and .getRawOne
    * @param rawData
    * @param deletePrefixes
    */
   public static cleanupGetRaw(rawData: RawData | Array<RawData>, deletePrefixes: Array<string> = []): any {
      let newName: string, prefixStr: string;

      const cleanupRow = (row: RawData) => {
         for (const prop in row) {
            if (row.hasOwnProperty(prop)) {
               newName = prop;
               deletePrefixes.map(prefix => {
                  prefixStr = prefix + '_';
                  if (newName.startsWith(prefixStr)) {
                     newName = newName.replace(prefixStr, '');
                  }
               });
               newName = camelCase(newName);
               this.renameObjectProperty(row, prop, newName);
            }
         }
      };

      // Support array or single object
      if (rawData instanceof Array) {
         for (const row of rawData) {
            cleanupRow(row);
         }
      } else {
         cleanupRow(rawData);
      }

      return rawData;
   }

   /**
    * Rename property in object
    * https://stackoverflow.com/questions/4647817/javascript-object-rename-key
    * @param obj
    * @param oldKey
    * @param newKey
    */
   public static renameObjectProperty(obj: any, oldKey: string, newKey: string): any {
      if (oldKey !== newKey) {
         Object.defineProperty(obj, newKey, Object.getOwnPropertyDescriptor(obj, oldKey));
         delete obj[oldKey];
      }
   }

from typeorm-naming-strategies.

btxtiger avatar btxtiger commented on May 30, 2024

I'm running again into that naming issue. Can't it be possible that there is really one?

getRepository(PublicChannelMessage)
    .createQueryBuilder('message')
    .select()
    .addSelect(qb => {
        return qb
            .select('SUM(vote1.weight)', 'total')
            .from('public_channel_message_vote', 'vote1')
            .leftJoin('public_channel_message', 'message1', 'vote1.ofMessage = message1.publicChannelMessageId')
            .where('vote1.ofMessage = message.publicChannelMessageId');
    }, 'totalWeight')
    .where('message.ofChannel = :id', { id: channelId })
    .getRawMany()

The issue occurres for subqueries. When I'm writing the camelCase name, the query will fail. Outside the subquery it works as usual.
.from('publicChannelMessageVote'
.leftJoin('publicChannelMessage'

 code: 'ER_NO_SUCH_TABLE',
  errno: 1146,
  sqlMessage:
   'Table \'chat_orm.publicchannelmessagevote\' doesn\'t exist',
  sqlState: '42S02',
  index: 0,

from typeorm-naming-strategies.

tonivj5 avatar tonivj5 commented on May 30, 2024

Hi @btxtiger, I'm trying to replicate your error but I can't. I'm using a subquery as you and it's working like it's expected 😕

from typeorm-naming-strategies.

tonivj5 avatar tonivj5 commented on May 30, 2024

Anyway, If it's failing It's an error of typeorm, because the expected behavior is that translate the camelCase name to snake_case. Are you sure that your table is registered or that's the correct name?

from typeorm-naming-strategies.

Related Issues (16)

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.