1
|
|
|
package sqlite |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"adrianolaselva.github.io/csvql/pkg/storage" |
5
|
|
|
"database/sql" |
6
|
|
|
"fmt" |
7
|
|
|
"strings" |
8
|
|
|
) |
9
|
|
|
|
10
|
|
|
const ( |
11
|
|
|
sqlCreateTableTemplate = "CREATE TABLE rows (%s\n);" |
12
|
|
|
sqlInsertTemplate = "INSERT INTO %s (%s) VALUES (%s);" |
13
|
|
|
defaultTableName = "rows" |
14
|
|
|
dataSourceNameDefault = ":memory:" |
15
|
|
|
) |
16
|
|
|
|
17
|
|
|
type sqLiteStorage struct { |
18
|
|
|
db *sql.DB |
19
|
|
|
tableName string |
20
|
|
|
columns []string |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
func NewSqLiteStorage(datasource string) (storage.Storage, error) { |
24
|
|
|
if datasource == "" { |
25
|
|
|
datasource = dataSourceNameDefault |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
db, err := sql.Open("sqlite3", datasource) |
29
|
|
|
if err != nil { |
30
|
|
|
return nil, err |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
return &sqLiteStorage{db: db, tableName: defaultTableName}, nil |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
func (s *sqLiteStorage) SetTableName(tableName string) storage.Storage { |
37
|
|
|
s.tableName = tableName |
38
|
|
|
return s |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
func (s *sqLiteStorage) SetColumns(columns []string) storage.Storage { |
42
|
|
|
s.columns = columns |
43
|
|
|
return s |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// BuildStructure build table creation statement |
47
|
|
|
func (s *sqLiteStorage) BuildStructure() error { |
48
|
|
|
var tableAttrsRaw strings.Builder |
49
|
|
|
for i, v := range s.columns { |
50
|
|
|
tableAttrsRaw.WriteString(fmt.Sprintf("\n\t%s text", v)) |
51
|
|
|
if len(s.columns)-1 > i { |
52
|
|
|
tableAttrsRaw.WriteString(",") |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
query := fmt.Sprintf(sqlCreateTableTemplate, tableAttrsRaw.String()) |
57
|
|
|
if _, err := s.db.Exec(query); err != nil { |
58
|
|
|
return fmt.Errorf("failed to create structure: %s (sql: %s)", err, query) |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return nil |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// InsertRow build insert create statement |
65
|
|
|
func (s *sqLiteStorage) InsertRow(values []any) error { |
66
|
|
|
columnsRaw := strings.Join(s.columns, ", ") |
67
|
|
|
paramsRaw := strings.Repeat("?, ", len(s.columns)) |
68
|
|
|
query := fmt.Sprintf(sqlInsertTemplate, s.tableName, columnsRaw, paramsRaw[:len(paramsRaw)-2]) |
69
|
|
|
|
70
|
|
|
if _, err := s.db.Exec(query, values...); err != nil { |
71
|
|
|
return fmt.Errorf("failed to execute insert: %s (sql: %s)", err, query) |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return nil |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
// Query execute statements |
78
|
|
|
func (s *sqLiteStorage) Query(cmd string) (*sql.Rows, error) { |
79
|
|
|
return s.db.Query(cmd) |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
// Close execute in defer |
83
|
|
|
func (s *sqLiteStorage) Close() error { |
84
|
|
|
return s.db.Close() |
85
|
|
|
} |
86
|
|
|
|