How can I befriend Gorm and Sqlx?

172 views Asked by At

I have a medium codebase based on GORM, but I also want to use Sqlx. If you want to ask why I chose sqlx in cooperation with gorm the answer is: easy to debug and no reflections.

But at this moment I can't reuse an existing connection between GORM and SQLX because they don't allow to reuse an already opened connection. And it is very difficult to manipulate through 2 connections instead of 1. At least the option pattern requires doing the same thing to both of objects: GORM and SQLX. Let's take an example:

type PostgreSQL struct {
    Gorm *gorm.DB
    Sqlx *sqlx.DB
    conn *sql.DB // it could be the same to Gorm and Sqlx
}

func NewPostgreSQL(dsn string, options ...func(*PostgreSQL)) (PostgreSQL, error) {
    gormdb, err := gorm.Open(postgres.Open(dsn))
    if err != nil {
        return PostgreSQL{}, err
    }

    sqlxdb, err := sqlx.Connect("postgres", dsn)
    if err != nil {
        return PostgreSQL{}, err
    }

    ps := &PostgreSQL{
        Gorm: gormdb,
        Sqlx: sqlxdb,
        conn: sqlxdb.DB, // I can't because it will only be applied on sqlxdb connection
    }
    for _, opt := range options {
        opt(ps)
    }

    return *ps, nil
}

func WithMaxIdleConns(conns int) func(*PostgreSQL) {
    return func(ps *PostgreSQL) {
        // This part of code could be simplified just to: ps.conn.SetMaxIdleConns(conns)
        db, err := ps.Gorm.DB()
        if err != nil {
            panic(err)
        }
        db.SetMaxIdleConns(conns)
        ps.Sqlx.SetMaxIdleConns(conns)
    }
}

And this is only the tip of the iceberg.

But, I can't understand why GORM doesn't allow using the already existing connection *sql.DB (in new versions you don't have Conn field in gorm.Config structure).
Note: on the site says:

Existing database connection GORM allows to initialize *gorm.DB with an existing database connection

import (
  "database/sql"
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
)

sqlDB, err := sql.Open("pgx", "mydb_dsn")
gormDB, err := gorm.Open(postgres.New(postgres.Config{
  Conn: sqlDB,
}), &gorm.Config{})

Also I don't have any idea why sqlx doesn't allow to reuse an existing DB connection.

Maybe this is because of some pitfalls I don't know about? What am I supposed to do? Should I make forks of GORM and SQLX and add missing functionality?

0

There are 0 answers