Test Failed
Push — add-integration-tests ( dde5b7...e98ac5 )
by Frank
02:26
created

database.*SQLite.Version   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
dl 0
loc 7
c 0
b 0
f 0
ccs 0
cts 2
cp 0
crap 6
rs 10
nop 0
1
package database
2
3
import (
4
	"database/sql"
5
	"fmt"
6
	"net/url"
7
	"strings"
8
9
	"github.com/fraenky8/tables-to-go/pkg/settings"
10
)
11
12
// SQLite implemenmts the Database interface with help of generalDatabase
13
type SQLite struct {
14
	*GeneralDatabase
15
}
16
17
// NewSQLite creates a new SQLite database
18
func NewSQLite(s *settings.Settings) *SQLite {
19 1
	return &SQLite{
20
		GeneralDatabase: &GeneralDatabase{
21
			Settings: s,
22
			driver:   dbTypeToDriverMap[s.DbType],
23
		},
24
	}
25
}
26
27
func (s *SQLite) Connect() (err error) {
28
	return s.GeneralDatabase.Connect(s.DSN())
29
}
30
31
func (s *SQLite) DSN() string {
32 1
	if s.Settings.User == "" && s.Settings.Pswd == "" {
33 1
		return fmt.Sprintf("%v", s.Settings.DbName)
34
	}
35
36 1
	u, err := url.Parse(s.DbName)
37 1
	if err != nil {
38 1
		return fmt.Sprintf("%v", s.Settings.DbName)
39
	}
40
41 1
	query := u.Query()
42 1
	query.Set("_auth_user", s.Settings.User)
43 1
	query.Set("_auth_pass", s.Settings.Pswd)
44 1
	u.RawQuery = query.Encode()
45
46
	// SQLite driver expects a empty `_auth` request param
47 1
	return strings.ReplaceAll(u.RequestURI(), "_auth=&", "_auth&")
48
}
49
50
// Version reports the actual version of the Sqlite database.
51
func (s *SQLite) Version() (string, error) {
52
	var version string
53
	err := s.Get(&version, `SELECT * FROM PRAGMA user_version`)
54
	if err != nil {
55
		return "", err
56
	}
57
	return version, nil
58
}
59
60
func (s *SQLite) GetDriverImportLibrary() string {
61
	return `"github.com/mattn/go-sqlite3"`
62
}
63
64
func (s *SQLite) GetTables() (tables []*Table, err error) {
65
66
	err = s.Select(&tables, `
67
		SELECT name AS table_name
68
		FROM sqlite_master
69
		WHERE type = 'table'
70
		AND name NOT LIKE 'sqlite?_%' escape '?'
71
	`)
72
73
	if s.Verbose {
74
		if err != nil {
75
			fmt.Println("> Error at GetTables()")
76
			fmt.Printf("> database: %q\r\n", s.DbName)
77
		}
78
	}
79
80
	return tables, err
81
}
82
83
func (s *SQLite) PrepareGetColumnsOfTableStmt() (err error) {
84
	return nil
85
}
86
87
func (s *SQLite) GetColumnsOfTable(table *Table) (err error) {
88
89
	rows, err := s.Queryx(`
90
		SELECT * 
91
		FROM PRAGMA_TABLE_INFO('` + table.Name + `')
92
	`)
93
	if err != nil {
94
		if s.Verbose {
95
			fmt.Printf("> Error at GetColumnsOfTable(%v)\r\n", table.Name)
96
			fmt.Printf("> database: %q\r\n", s.DbName)
97
		}
98
		return err
99
	}
100
101
	type column struct {
102
		CID          int            `db:"cid"`
103
		Name         string         `db:"name"`
104
		DataType     string         `db:"type"`
105
		NotNull      int            `db:"notnull"`
106
		DefaultValue sql.NullString `db:"dflt_value"`
107
		PrimaryKey   int            `db:"pk"`
108
	}
109
110
	for rows.Next() {
111
		var col column
112
		err = rows.StructScan(&col)
113
		if err != nil {
114
			return err
115
		}
116
117
		isNullable := "YES"
118
		if col.NotNull == 1 {
119
			isNullable = "NO"
120
		}
121
122
		isPrimaryKey := ""
123
		if col.PrimaryKey == 1 {
124
			isPrimaryKey = "PK"
125
		}
126
127
		table.Columns = append(table.Columns, Column{
128
			OrdinalPosition:        col.CID,
129
			Name:                   col.Name,
130
			DataType:               col.DataType,
131
			DefaultValue:           col.DefaultValue,
132
			IsNullable:             isNullable,
133
			CharacterMaximumLength: sql.NullInt64{},
134
			NumericPrecision:       sql.NullInt64{},
135
			// reuse mysql column_key as primary key indicator
136
			ColumnKey:      isPrimaryKey,
137
			Extra:          "",
138
			ConstraintName: sql.NullString{},
139
			ConstraintType: sql.NullString{},
140
		})
141
	}
142
143
	return nil
144
}
145
146
func (s *SQLite) IsPrimaryKey(column Column) bool {
147
	return column.ColumnKey == "PK"
148
}
149
150
func (s *SQLite) IsAutoIncrement(column Column) bool {
151
	return column.ColumnKey == "PK"
152
}
153
154
func (s *SQLite) GetStringDatatypes() []string {
155
	return []string{
156
		"text",
157
	}
158
}
159
160
func (s *SQLite) IsString(column Column) bool {
161
	return s.IsStringInSlice(column.DataType, s.GetStringDatatypes())
162
}
163
164
func (s *SQLite) GetTextDatatypes() []string {
165
	return []string{
166
		"text",
167
	}
168
}
169
170
func (s *SQLite) IsText(column Column) bool {
171
	return s.IsStringInSlice(column.DataType, s.GetTextDatatypes())
172
}
173
174
func (s *SQLite) GetIntegerDatatypes() []string {
175
	return []string{
176
		"integer",
177
	}
178
}
179
180
func (s *SQLite) IsInteger(column Column) bool {
181
	return s.IsStringInSlice(column.DataType, s.GetIntegerDatatypes())
182
}
183
184
func (s *SQLite) GetFloatDatatypes() []string {
185
	return []string{
186
		"real",
187
		"numeric",
188
	}
189
}
190
191
func (s *SQLite) IsFloat(column Column) bool {
192
	return s.IsStringInSlice(column.DataType, s.GetFloatDatatypes())
193
}
194
195
func (s *SQLite) GetTemporalDatatypes() []string {
196
	return []string{}
197
}
198
199
func (s *SQLite) IsTemporal(column Column) bool {
200
	return false
201
}
202
203
func (s *SQLite) GetTemporalDriverDataType() string {
204
	return ""
205
}
206