aboutsummaryrefslogtreecommitdiffstats
path: root/internal/storage/mssql.go
blob: 02b2108730c0e04b43b7adf2bcab7fcef96bea8a (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
package storage

import (
	"fmt"
	"strings"
)

type MSSQLAdapter struct{}

func (m MSSQLAdapter) ConvertGenericPlaceholders(
	query string,
	argsCount int,
) string {
	for i := 0; i <= argsCount; i++ {
		placeholder := m.createPlaceholder(i + 1)
		query = strings.Replace(query, "?", placeholder, 1)
	}
	return query
}

func (m MSSQLAdapter) createPlaceholder(index int) string {
	return fmt.Sprintf("@p%d", index)
}

func (m MSSQLAdapter) TableExists(
	executor sqlExecutor,
	tableName string,
) (bool, error) {
	var exists bool

	schemaName := "dbo"
	parts := strings.Split(tableName, ".")
	if len(parts) == 2 {
		schemaName = parts[0]
		tableName = parts[1]
	} else {
		tableName = parts[0]
	}

	err := executor.QueryRow(`
		SELECT CASE WHEN EXISTS (
			SELECT * 
			FROM INFORMATION_SCHEMA.TABLES 
			WHERE TABLE_SCHEMA = @p1
			AND TABLE_NAME = @p2
		) THEN 1 ELSE 0 END
	`, schemaName, tableName).Scan(&exists)
	if err != nil {
		return false, fmt.Errorf(
			"unable to check if %s exists: %w",
			tableName,
			err,
		)
	}

	return exists, nil
}

func (m MSSQLAdapter) DatabaseName(executor sqlExecutor) (string, error) {
	var name string
	err := executor.QueryRow("SELECT DB_NAME();").Scan(&name)
	if err != nil {
		return "", fmt.Errorf("unable to retrieve database name: %w", err)
	}

	return name, nil
}