New creates a new SQLite session service. dbPath is the path to the SQLite database file. If the file doesn't exist, it will be created.
(dbPath string)
| 29 | // dbPath is the path to the SQLite database file. |
| 30 | // If the file doesn't exist, it will be created. |
| 31 | func New(dbPath string) (*Service, error) { |
| 32 | db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL&_busy_timeout=5000") |
| 33 | if err != nil { |
| 34 | return nil, fmt.Errorf("open sqlite database: %w", err) |
| 35 | } |
| 36 | |
| 37 | // Set connection pool settings for SQLite |
| 38 | db.SetMaxOpenConns(1) // SQLite only supports one writer |
| 39 | db.SetMaxIdleConns(1) |
| 40 | db.SetConnMaxLifetime(time.Hour) |
| 41 | |
| 42 | s := &Service{db: db} |
| 43 | |
| 44 | if err := s.migrate(); err != nil { |
| 45 | _ = db.Close() // Ignore close error, migration error is more important |
| 46 | return nil, fmt.Errorf("migrate database: %w", err) |
| 47 | } |
| 48 | |
| 49 | return s, nil |
| 50 | } |
| 51 | |
| 52 | // migrate creates the necessary tables if they don't exist. |
| 53 | func (s *Service) migrate() error { |