package data import ( "fmt" "strings" "github.com/jmoiron/sqlx" _ "github.com/mattn/go-sqlite3" "crypto/rand" "encoding/hex" ) var schema = ` CREATE TABLE IF NOT EXISTS commit_log ( id VARCHAR(255) PRIMARY KEY, msg VARCHAR(255), created_at DATETIME, editor VARCHAR(255), change_file VARCHAR(255), relation VARCHAR(255) ); ` type CommitLog struct { Id string `db:"id"` Msg string `db:"msg"` Created_at string `db:"created_at"` Editor string `db:"editor"` Change_file string `db:"change_file"` Relation string `db:"relation"` } func HashCommit(n int) (string, error) { // _, err := h.Write([]byte(target)) // if err != nil { // Log.Debug("Error when hashing commit", zap.Error(err)) // return "", err // } // return string(h.Sum(nil)), nil byt := make([]byte, n) _, err := rand.Read(byt) if err != nil { return "", err } return hex.EncodeToString(byt), nil } func Insert(c *CommitLog) error { commit_db, err := sqlx.Connect("sqlite3", "./data/database.db") if err != nil { } // init table in db commit_db.MustExec(schema) _, err = commit_db.NamedExec("INSERT INTO commit_log (id, msg, created_at, editor, change_file, relation) VALUES (:id, :msg, :created_at, :editor, :change_file, :relation)", c) if err != nil { return err } return nil } func GetCommitLogOfFilename(countryId string, filename string) ([]CommitLog, error) { filename = strings.TrimSuffix(filename, ".json") // try split and get pos 1 and 2 filenameParts := strings.Split(filename, "_") if len(filenameParts) == 2 { filename = filenameParts[1] } else if len(filenameParts) > 2 { filename = filenameParts[1] + "_" + filenameParts[2] } commitDB, err := sqlx.Connect("sqlite3", "./data/database.db") // fmt.Println("GetCommitLogOfFilename", err) if err != nil { return nil, err } var commits []CommitLog // get contains // err = commitDB.Get(&commits, "SELECT * FROM commit_log WHERE change_file LIKE ?", "%"+filename+"%") err = commitDB.Select(&commits, "SELECT * FROM commit_log WHERE change_file LIKE ?", "%"+filename+"%") // fmt.Println("commits", err) if err != nil { return nil, err } var commitsByCountryID []CommitLog for _, v := range commits { if strings.Contains(v.Change_file, countryId) { // do convert time format v.Created_at = strings.Replace(v.Created_at, "T", " ", -1) v.Created_at = strings.Replace(v.Created_at, "Z", "", -1) commitsByCountryID = append(commitsByCountryID, v) } } if err != nil { return nil, err } // fmt.Println("commitsByCountryID", len(commitsByCountryID) == 0) if len(commitsByCountryID) == 0 { return nil, fmt.Errorf("no commit found for %s", filename) } return commitsByCountryID, nil } func GetCommitLogs() ([]CommitLog, error) { commit_db, err := sqlx.Connect("sqlite3", "./data/database.db") if err != nil { } var commits []CommitLog err = commit_db.Get(&commits, "SELECT * FROM commit_log", nil) if err != nil { return nil, err } return commits, nil }