adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.07k stars 191 forks source link

I have problem with cast mysql charactor set tis620 to utf8 when I use following solution #928

Closed ingus-indigo closed 1 year ago

ingus-indigo commented 1 year ago

I have problem with cast mysql charactor set tis620 to utf8 when I use following solution

My Coding using by route middleware

.middleware(async (ctx, next) => {
    await Database.connection().rawQuery('SET NAMES UTF8')
    await next()
})

The result correctly but somtime the result not cast to utf8, I think because they use different connections

I'm try another solution (inline casting)

await Database.connection().rawQuery('SET NAMES UTF8')
const terminalItemInfo = await TerminalItemInfo.query()
....
})

Above code give me the same middleware problem

Finaly when i try to use database transaction

let trx = await Database.connection().transaction()
await trx.rawQuery('SET NAMES UTF8')
let terminalItemInfo = await TerminalItemInfo.query({ client: trx })...
await trx.commit()
....
})

OR use hook by override BaseModel

export default class ModelUTF8 extends BaseModel {
  public static async boot(){
    if (this.booted) {
      return
    }

    super.boot()
  }

  @beforeFetch()
  public static async fetchUtf8(modelInstance) {
    await this.castUTF8(modelInstance)
  }

  @beforeFind()
  public static async findUtf8(modelInstance) {
    await this.castUTF8(modelInstance)
  }

  private static async castUTF8(modelInstance) {
    if (modelInstance.$trx) {
      await modelInstance.$trx.rawQuery('SET NAMES UTF8')
    }
  }
....
})

This solution solves the problem perfectly no more distorted language came out

Finaly i need solve my problem for best practices solution my solution depen on transaction only, can i solve this with out useing transaction?

ingus-indigo commented 1 year ago

how about possible to add afterConnect hook and return connection from callback then i can force every connection to "SET NAME UTF8" i think this is the best way?

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.