(ctx context.Context, config *csconfig.DatabaseCfg, logger *log.Entry)
| 41 | } |
| 42 | |
| 43 | func NewClient(ctx context.Context, config *csconfig.DatabaseCfg, logger *log.Entry) (*Client, error) { |
| 44 | var client *ent.Client |
| 45 | |
| 46 | if logger == nil { |
| 47 | logger = log.StandardLogger().WithFields(nil) |
| 48 | } |
| 49 | |
| 50 | if config == nil { |
| 51 | return nil, errors.New("DB config is empty") |
| 52 | } |
| 53 | |
| 54 | entLogger := logger.WithField("context", "ent") |
| 55 | entOpt := ent.Log(entLogger.Debug) |
| 56 | |
| 57 | typ, dia, err := config.ConnectionDialect() |
| 58 | if err != nil { |
| 59 | return nil, err // unsupported database caught here |
| 60 | } |
| 61 | |
| 62 | if config.Type == "sqlite" && config.DbPath != ":memory:" { |
| 63 | /*if it's the first startup, we want to touch and chmod file*/ |
| 64 | if _, err = os.Stat(config.DbPath); os.IsNotExist(err) { |
| 65 | f, err := os.OpenFile(config.DbPath, os.O_CREATE|os.O_RDWR, 0o600) |
| 66 | if err != nil { |
| 67 | return nil, fmt.Errorf("failed to create SQLite database file %q: %w", config.DbPath, err) |
| 68 | } |
| 69 | |
| 70 | if err := f.Close(); err != nil { |
| 71 | return nil, fmt.Errorf("failed to create SQLite database file %q: %w", config.DbPath, err) |
| 72 | } |
| 73 | } |
| 74 | // Always try to set permissions to simplify a bit the code for windows (as the permissions set by OpenFile will be garbage) |
| 75 | if err = setFilePerm(config.DbPath, 0o640); err != nil { |
| 76 | return nil, fmt.Errorf("unable to set perms on %s: %w", config.DbPath, err) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | dbConnectionString, err := config.ConnectionString() |
| 81 | if err != nil { |
| 82 | return nil, fmt.Errorf("failed to generate DB connection string: %w", err) |
| 83 | } |
| 84 | |
| 85 | drv, err := getEntDriver(typ, dia, dbConnectionString, config) |
| 86 | if err != nil { |
| 87 | return nil, fmt.Errorf("failed opening connection to %s: %w", config.Type, err) |
| 88 | } |
| 89 | |
| 90 | client = ent.NewClient(ent.Driver(drv), entOpt) |
| 91 | |
| 92 | if config.LogLevel >= log.DebugLevel { |
| 93 | logger.Debugf("Enabling request debug") |
| 94 | |
| 95 | client = client.Debug() |
| 96 | } |
| 97 | |
| 98 | if err = client.Schema.Create(ctx); err != nil { |
| 99 | return nil, fmt.Errorf("failed creating schema resources: %w", err) |
| 100 | } |
searching dependent graphs…