| 102 | } |
| 103 | |
| 104 | func initSQLDatabase(c *config.DatabaseConfig, tp trace.TracerProvider, log *log.Helper) (*ent.Client, *sql.DB, error) { |
| 105 | if c.Driver != "pgx" { |
| 106 | return nil, nil, fmt.Errorf("unsupported driver: %s", c.Driver) |
| 107 | } |
| 108 | |
| 109 | log.Debugf("connecting to db: driver=%s", c.Driver) |
| 110 | |
| 111 | db, err := otelsql.Open(c.Driver, c.Source, |
| 112 | otelsql.WithTracerProvider(tp), |
| 113 | otelsql.WithAttributes(semconv.DBSystemPostgreSQL), |
| 114 | otelsql.WithSpanOptions(otelsql.SpanOptions{ |
| 115 | DisableErrSkip: true, |
| 116 | OmitRows: true, |
| 117 | OmitConnResetSession: true, |
| 118 | OmitConnPrepare: true, |
| 119 | OmitConnectorConnect: true, |
| 120 | }), |
| 121 | ) |
| 122 | if err != nil { |
| 123 | return nil, nil, fmt.Errorf("error opening the connection, driver=%s: %w", c.Driver, err) |
| 124 | } |
| 125 | |
| 126 | if c.MaxOpenConns > 0 { |
| 127 | log.Infof("DB: setting max open conns: %d", c.MaxOpenConns) |
| 128 | db.SetMaxOpenConns(int(c.MaxOpenConns)) |
| 129 | } |
| 130 | |
| 131 | if n := c.MinOpenConns; n > 0 { |
| 132 | // database/sql has no MinOpenConns; MaxIdleConns keeps idle connections warm which is the closest equivalent |
| 133 | log.Infof("DB: setting max idle conns (from min_open_conns): %v", n) |
| 134 | db.SetMaxIdleConns(int(n)) |
| 135 | } |
| 136 | |
| 137 | if t := c.MaxConnIdleTime.AsDuration(); t > 0 { |
| 138 | log.Infof("DB: setting max conn idle time: %v", t) |
| 139 | db.SetConnMaxIdleTime(t) |
| 140 | } |
| 141 | |
| 142 | drv := entsql.OpenDB(dialect.Postgres, db) |
| 143 | client := ent.NewClient(ent.Driver(drv)) |
| 144 | |
| 145 | // NOTE: We do not run migrations automatically anymore |
| 146 | // Instead we leverage atlas cli to run migrations |
| 147 | return client, db, nil |
| 148 | } |
| 149 | |
| 150 | func toTimePtr(t time.Time) *time.Time { |
| 151 | if t.IsZero() { |