aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/gitea.com/lunny/log/dbwriter.go
blob: e8ff00bd8964376c7ee18767b6ec9976912ca21f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package log

import (
	"database/sql"
	"time"
)

type DBWriter struct {
	db      *sql.DB
	stmt    *sql.Stmt
	content chan []byte
}

func NewDBWriter(db *sql.DB) (*DBWriter, error) {
	_, err := db.Exec("CREATE TABLE IF NOT EXISTS log (id int, content text, created datetime)")
	if err != nil {
		return nil, err
	}
	stmt, err := db.Prepare("INSERT INTO log (content, created) values (?, ?)")
	if err != nil {
		return nil, err
	}
	return &DBWriter{db, stmt, make(chan []byte, 1000)}, nil
}

func (w *DBWriter) Write(p []byte) (n int, err error) {
	_, err = w.stmt.Exec(string(p), time.Now())
	if err == nil {
		n = len(p)
	}
	return
}

func (w *DBWriter) Close() {
	w.stmt.Close()
}