File: sqltest.go

package info (click to toggle)
golang-ariga-atlas 0.7.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 5,676 kB
  • sloc: javascript: 592; sql: 404; makefile: 10
file content (72 lines) | stat: -rw-r--r-- 2,004 bytes parent folder | download
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
// Copyright 2021-present The Atlas Authors. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.

package sqltest

import (
	"database/sql/driver"
	"regexp"
	"strings"
	"unicode"

	"github.com/DATA-DOG/go-sqlmock"
)

// Rows converts MySQL/PostgreSQL table output to sql.Rows.
// All row values are parsed as text except the "nil" and NULL keywords.
// For example:
//
// 		+-------------+-------------+-------------+----------------+
//		| column_name | column_type | is_nullable | column_default |
//		+-------------+-------------+-------------+----------------+
//		| c1          | float       | YES         | nil            |
//		| c2          | int         | YES         |                |
//		| c3          | double      | YES         | NULL           |
//		+-------------+-------------+-------------+----------------+
//
func Rows(table string) *sqlmock.Rows {
	var (
		nc    int
		rows  *sqlmock.Rows
		lines = strings.Split(table, "\n")
	)
	for i := 0; i < len(lines); i++ {
		line := strings.TrimFunc(lines[i], unicode.IsSpace)
		// Skip new lines, header and footer.
		if line == "" || strings.IndexAny(line, "+-") == 0 {
			continue
		}
		columns := strings.FieldsFunc(line, func(r rune) bool {
			return r == '|'
		})
		for i, c := range columns {
			columns[i] = strings.TrimSpace(c)
		}
		if rows == nil {
			nc = len(columns)
			rows = sqlmock.NewRows(columns)
		} else {
			values := make([]driver.Value, nc)
			for i, c := range columns {
				switch c {
				case "", "nil", "NULL":
				default:
					values[i] = c
				}
			}
			rows.AddRow(values...)
		}
	}
	return rows
}

// Escape escapes all regular expression metacharacters in the given query.
func Escape(query string) string {
	rows := strings.Split(query, "\n")
	for i := range rows {
		rows[i] = strings.TrimPrefix(rows[i], " ")
	}
	query = strings.Join(rows, " ")
	return strings.TrimSpace(regexp.QuoteMeta(query)) + "$"
}