Open initialize db session based on dialector
(dialector Dialector, opts ...Option)
| 136 | |
| 137 | // Open initialize db session based on dialector |
| 138 | func Open(dialector Dialector, opts ...Option) (db *DB, err error) { |
| 139 | config := &Config{} |
| 140 | |
| 141 | sort.Slice(opts, func(i, j int) bool { |
| 142 | _, isConfig := opts[i].(*Config) |
| 143 | _, isConfig2 := opts[j].(*Config) |
| 144 | return isConfig && !isConfig2 |
| 145 | }) |
| 146 | |
| 147 | if len(opts) > 0 { |
| 148 | if c, ok := opts[0].(*Config); ok { |
| 149 | config = c |
| 150 | } else { |
| 151 | opts = append([]Option{config}, opts...) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | var skipAfterInitialize bool |
| 156 | for _, opt := range opts { |
| 157 | if opt != nil { |
| 158 | if applyErr := opt.Apply(config); applyErr != nil { |
| 159 | return nil, applyErr |
| 160 | } |
| 161 | defer func(opt Option) { |
| 162 | if skipAfterInitialize { |
| 163 | return |
| 164 | } |
| 165 | if errr := opt.AfterInitialize(db); errr != nil { |
| 166 | err = errr |
| 167 | } |
| 168 | }(opt) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if d, ok := dialector.(interface{ Apply(*Config) error }); ok { |
| 173 | if err = d.Apply(config); err != nil { |
| 174 | return |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | if config.NamingStrategy == nil { |
| 179 | config.NamingStrategy = schema.NamingStrategy{IdentifierMaxLength: 64} // Default Identifier length is 64 |
| 180 | } |
| 181 | |
| 182 | if config.Logger == nil { |
| 183 | config.Logger = logger.Default |
| 184 | } |
| 185 | |
| 186 | if config.NowFunc == nil { |
| 187 | config.NowFunc = func() time.Time { return time.Now().Local() } |
| 188 | } |
| 189 | |
| 190 | if dialector != nil { |
| 191 | config.Dialector = dialector |
| 192 | } |
| 193 | |
| 194 | if config.Plugins == nil { |
| 195 | config.Plugins = map[string]Plugin{} |