chaosblade
106 строк · 2.2 Кб
1/*
2* Copyright 1999-2020 Alibaba Group Holding Ltd.
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package data
18
19import (
20"context"
21"database/sql"
22"fmt"
23"github.com/chaosblade-io/chaosblade-spec-go/log"
24"path"
25"sync"
26"unicode"
27
28"github.com/chaosblade-io/chaosblade-spec-go/util"
29_ "github.com/mattn/go-sqlite3"
30)
31
32const dataFile = "chaosblade.dat"
33
34type SourceI interface {
35ExperimentSource
36PreparationSource
37}
38
39type Source struct {
40DB *sql.DB
41}
42
43var source SourceI
44var once = sync.Once{}
45
46func GetSource() SourceI {
47once.Do(func() {
48src := &Source{
49DB: getConnection(),
50}
51src.init()
52source = src
53})
54return source
55}
56
57const tableExistsDQL = `SELECT count(*) AS c
58FROM sqlite_master
59WHERE type = "table"
60AND name = ?
61`
62
63func (s *Source) init() {
64s.CheckAndInitExperimentTable()
65s.CheckAndInitPreTable()
66}
67
68func getConnection() *sql.DB {
69database, err := sql.Open("sqlite3", path.Join(util.GetProgramPath(), dataFile))
70if err != nil {
71log.Fatalf(context.Background(), "open data file err, %s", err.Error())
72//log.Error(err, "open data file err")
73//os.Exit(1)
74}
75return database
76}
77
78func (s *Source) Close() {
79if s.DB != nil {
80s.DB.Close()
81}
82}
83
84// GetUserVersion returns the user_version value
85func (s *Source) GetUserVersion() (int, error) {
86userVerRows, err := s.DB.Query("PRAGMA user_version")
87if err != nil {
88return 0, err
89}
90defer userVerRows.Close()
91var userVersion int
92for userVerRows.Next() {
93userVerRows.Scan(&userVersion)
94}
95return userVersion, nil
96}
97
98// UpdateUserVersion to the latest
99func (s *Source) UpdateUserVersion(version int) error {
100_, err := s.DB.Exec(fmt.Sprintf("PRAGMA user_version=%d", version))
101return err
102}
103
104func UpperFirst(str string) string {
105return string(unicode.ToUpper(rune(str[0]))) + str[1:]
106}
107