aboutsummaryrefslogtreecommitdiffstats
path: root/internal/sqlparse/sqlparse_test.go
blob: 5fe58fa626aa6f030acf7d33c3c47cf2850ab092 (plain) (blame)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package sqlparse_test

import (
	"bytes"
	"errors"
	"io"
	"strings"
	"testing"

	"github.com/eugenetriguba/bolt/internal/sqlparse"
	"github.com/eugenetriguba/checkmate/assert"
)

func TestSqlParser_Parse(t *testing.T) {
	testCases := []struct {
		buffer                   string
		expectedExecutionOptions *sqlparse.ExecutionOptions
	}{
		{
			buffer:                   "-- bolt: no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: false},
		},
		{
			buffer:                   "-- BOLT: no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: false},
		},
		{
			buffer:                   "\n-- bolt: no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: true},
		},
		{
			buffer:                   "",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: true},
		},
		{
			buffer:                   "--bolt: no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: true},
		},
		{
			buffer:                   "-- bolt : no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: true},
		},
		{
			buffer:                   "-- bolt: no-transaction no-transaction",
			expectedExecutionOptions: &sqlparse.ExecutionOptions{UseTransaction: false},
		},
	}

	for _, tc := range testCases {
		sqlParser := sqlparse.NewSqlParser(strings.NewReader(tc.buffer))

		execOptions, err := sqlParser.Parse()
		assert.Nil(t, err)

		assert.DeepEqual(t, execOptions, tc.expectedExecutionOptions)
	}
}

type ErrReader struct {
	Reader  io.Reader
	ErrCond string
}

func (er *ErrReader) Read(p []byte) (int, error) {
	n, err := er.Reader.Read(p)
	if err != nil {
		return n, err
	}

	if bytes.Contains(p[:n], []byte(er.ErrCond)) {
		return n, errors.New("error: unwanted input encountered")
	}

	return n, nil
}

func TestSqlParserParseError(t *testing.T) {
	reader := &ErrReader{
		Reader:  strings.NewReader("    "),
		ErrCond: " ",
	}
	sqlParser := sqlparse.NewSqlParser(reader)
	_, err := sqlParser.Parse()
	assert.NotNil(t, err)
	assert.ErrorContains(t, err, "unwanted input encountered")
}