Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(SQL Server): implement the batcher of SQL Server (#9623)

h3n4ldcc01e67d4cd
diff --git a/backend/plugin/parser/tsql/batch/batch.go b/backend/plugin/parser/tsql/batch/batch.go
new file mode 100644
index 0000000000..f1ca287bbc
--- /dev/null
+++ b/backend/plugin/parser/tsql/batch/batch.go
@@ -0,0 +1,262 @@
+package batch
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+)
+
+/*
+ * batch.go provides the ability to split a Transact-SQL script into batches.
+ * It is based on the github.com/microsoft/go-sqlcmd package, we can move to
+ * use it when it's documented and stable.
+ * Currently, we references the code from https://sourcegraph.com/github.com/microsoft/go-sqlcmd@fb920dc0da056e58969696128b440e2bf99c105b/-/blob/pkg/sqlcmd/batch.go?L76-170.
+ */
+
+const (
+ // minCapIncrease is the minimum number of bytes to grow the buffer by.
+ minCapIncrease = 512
+)
+
+type Command interface {
+ // isCommand is a dummy method to prevent users from implementing the Command interface.
+ isCommand()
+ // String returns the string representation of the command.
+ String() string
+}
+
+type baseCommand struct{}
+
+func (*baseCommand) isCommand() {}
+
+var (
+ // lineEnd is the slice to use when appending a line.
+ lineEnd = []rune("\n")
+
+ // commandsBuilder is a map of command names to functions that builds the command from input.
+ commandBuilders = map[string]func(string) Command{
+ "GO": buildGoCommand,
+ }
+
+ // goCommandMatcher matches a Go Command.
+ goCommandMatcher = regexp.MustCompile(fmt.Sprintf(`(?im)^[\t ]*?%s(?:[ ]+(.*$)|$)`, regexp.QuoteMeta("GO")))
+)
+
+// GoCommand signals the end of a batch of Transact-SQL statements to the SQL Server Utilities.
+// https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go?view=sql-server-ver16
+type GoCommand struct {
+ baseCommand
+ // Count is a positive integer, the batch preceding the GO command will execute the specified number of times.
+ // The default value of Count is 1.
+ Count uint
+}
+
+// String returns the string representation of the command.
+func (g *GoCommand) String() string {
+ return fmt.Sprintf("GO %d", g.Count)
+}
+
+func buildGoCommand(input string) Command {
+ matches := goCommandMatcher.FindStringSubmatch(input)
+ if matches == nil {
+ return nil
+ }
+ if len(matches) != 2 {
+ return nil
+ }
+
+ var n int
+ var err error
+ if matches[1] == "" {
+ n = 1
+ } else {
+ n, err = strconv.Atoi(matches[1])
+ if err != nil {
+ return nil
+ }
+ if n < 1 {
+ return nil
+ }
+ }
+
+ return &GoCommand{
+ Count: uint(n),
+ }
+}
+
+type Scan func() (string, error)
+
+type Batch struct {
+ // read provides the next chunk of runes.
+ read Scan
+ // buffer is the current batch text.
+ buffer []rune
+ // length is the length of the statement.
+ length int
+ // raw is the unprocessed runes.
+ raw []rune
+ // rawLen is the number of unprocessed rune.
+ rawLen int
+ // quote indicates currently processing a quoted string.
+ quote rune
+ // comment is the state of multi-line comment.
+ comment bool
+}
+
+// NewBatch returns a new Batch.
+func NewBatch(read Scan) *Batch {
+ return &Batch{
+ read: read,
+ }
+}
+
+// String returns the current SQL batch next.
+func (b *Batch) String() string {
+ return string(b.buffer)
+}
+
+// Next returns the next command in the batch.
+func (b *Batch) Next() (Command, error) {
+ var i int
+
+ if b.rawLen == 0 {
+ s, err := b.read()
+ if err != nil {
+ return nil, err
+ }
+ b.raw = []rune(s)
+ b.rawLen = len(b.raw)
+ }
+
+ var command Command
+ var ok bool
+ var scannedCommand bool
+
+parse:
+ for ; i < b.rawLen; i++ {
+ c, next := b.raw[i], grab(b.raw, i+1, b.rawLen)
+ switch {
+ // we're in a quoted string
+ case b.quote != 0:
+ i, ok = b.readString(b.raw, i, b.rawLen, b.quote)
+ if ok {
+ b.quote = 0
+ }
+ // inside a multiline comment
+ case b.comment:
+ i, ok = readMultilineComment(b.raw, i, b.rawLen)
+ b.comment = !ok
+ // start of a string
+ case c == '\'' || c == '"' || c == '[':
+ b.quote = c
+ // inline sql comment, skip to end of line
+ case c == '-' && next == '-':
+ i = b.rawLen
+ // start a multi-line comment
+ case c == '/' && next == '*':
+ b.comment = true
+ i++
+ // continue processing quoted string or multiline comment
+ case b.quote != 0 || b.comment:
+
+ // We do not care about the variable reference for now.
+ // Handle variable references
+ // case c == '$' && next == '(':
+ // vi, ok := readVariableReference(b.raw, i+2, b.rawLen)
+ // if ok {
+ // b.addVariableLocation(i, string(b.raw[i+2:vi]))
+ // i = vi
+
+ // } else {
+ // err = syntaxError(b.linecount)
+ // break parse
+ // }
+
+ // Commands have to be alone on the line
+ case !scannedCommand:
+ var cend int
+ scannedCommand = true
+ command, cend = readCommand(b.raw, i, b.rawLen)
+ if command != nil {
+ // remove the command from raw
+ b.raw = append(b.raw[:i], b.raw[cend:]...)
+ break parse
+ }
+ }
+ }
+
+ if command == nil {
+ i = min(i, b.rawLen)
+ b.append(b.raw[:i], lineEnd)
+ }
+ b.raw = b.raw[i:]
+ b.rawLen = len(b.raw)
+
+ return command, nil
+}
+
+// append appends r to b.Buffer separated by sep when b.Buffer is not already empty.
+//
+// Dynamically grows b.Buf as necessary to accommodate r and the separator.
+// Specifically, when b.Buf is not empty, b.Buf will grow by increments of
+// MinCapIncrease.
+//
+// After a call to append, b.Len will be len(b.Buf)+len(sep)+len(r). Call Reset
+// to reset the Buf.
+func (b *Batch) append(r, sep []rune) {
+ rlen := len(r)
+ // initial
+ if b.buffer == nil {
+ b.buffer, b.length = r, rlen
+ return
+ }
+ blen, seplen := b.length, len(sep)
+ tlen := blen + rlen + seplen
+ // grow
+ if bcap := cap(b.buffer); tlen > bcap {
+ n := tlen + 2*rlen
+ n += minCapIncrease - (n % minCapIncrease)
+ z := make([]rune, blen, n)
+ copy(z, b.buffer)
+ b.buffer = z
+ }
+ b.buffer = b.buffer[:tlen]
+ copy(b.buffer[blen:], sep)
+ copy(b.buffer[blen+seplen:], r)
+ b.length = tlen
+}
+
+// readString seeks to the end of a string returning the position and whether
+// or not the string's end was found.
+// If the string's terminator was not found, then the result will be the passed
+// end.
+func (*Batch) readString(r []rune, i, end int, quote rune) (int, bool) {
+ var prev, c, next rune
+ for ; i < end; i++ {
+ c, next = r[i], grab(r, i+1, end)
+ switch {
+ case quote == '\'' && c == '\'' && next == '\'',
+ quote == '[' && c == ']' && next == ']':
+ i++
+ continue
+ case quote == '\'' && c == '\'' && prev != '\'',
+ quote == '"' && c == '"',
+ quote == '[' && c == ']':
+ return i, true
+ }
+ prev = c
+ }
+ return end, false
+}
+
+// Reset clears the current batch text and replaces it with new runes.
+func (b *Batch) Reset(r []rune) {
+ b.buffer, b.length = nil, 0
+ b.quote = 0
+ b.comment = false
+ if r != nil {
+ b.raw, b.rawLen = r, len(r)
+ } else {
+ b.rawLen = 0
+ }
+}
diff --git a/backend/plugin/parser/tsql/batch/batch_test.go b/backend/plugin/parser/tsql/batch/batch_test.go
new file mode 100644
index 0000000000..0e5a092130
--- /dev/null
+++ b/backend/plugin/parser/tsql/batch/batch_test.go
@@ -0,0 +1,130 @@
+package batch
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v2"
+)
+
+func TestBuildGoCommands(t *testing.T) {
+ testCases := []struct {
+ input string
+ wantNil bool
+ wantCount uint
+ }{
+ {
+ input: "",
+ wantNil: true,
+ },
+ {
+ input: "GO 123",
+ wantNil: false,
+ wantCount: 123,
+ },
+ {
+ input: "GO [123]",
+ wantNil: true,
+ },
+ {
+ input: "GO -1",
+ wantNil: true,
+ },
+ }
+
+ a := require.New(t)
+
+ for _, tc := range testCases {
+ got := buildGoCommand(tc.input)
+ if tc.wantNil {
+ a.Nil(got)
+ } else {
+ goCmd, ok := got.(*GoCommand)
+ a.True(ok)
+ a.Equalf(tc.wantCount, goCmd.Count, "Input: %s", tc.input)
+ }
+ }
+}
+
+type batchResult struct {
+ Statements string `yaml:"statements"`
+ Command string `yaml:"command"`
+}
+
+func TestBatch(t *testing.T) {
+ type TestCase struct {
+ // input is the input string.
+ // The input string can be a single SQL statement or a batch of SQL statements.
+ Input string `yaml:"input"`
+ Description string `yaml:"description"`
+ Batches []batchResult `yaml:"batches"`
+ }
+
+ a := require.New(t)
+
+ filePath := "testdata/test_batch.yaml"
+ f, err := os.Open(filePath)
+ a.NoError(err)
+ defer f.Close()
+
+ bytes, err := io.ReadAll(f)
+ a.NoError(err)
+
+ var testCases []TestCase
+ a.NoError(yaml.Unmarshal(bytes, &testCases))
+
+ var record = true
+ for i, tc := range testCases {
+ batchResults := getBatchResults(a, tc.Input)
+ if record {
+ testCases[i].Batches = batchResults
+ } else {
+ a.Equalf(tc.Batches, batchResults, "Input: %s", tc.Input)
+ }
+ }
+ if record {
+ bytes, err := yaml.Marshal(testCases)
+ a.NoError(err)
+ a.NoError(os.WriteFile(filePath, bytes, 0644))
+ }
+}
+
+func getBatchResults(a *require.Assertions, input string) []batchResult {
+ s := strings.Split(input, "\n")
+ scanner := func() (string, error) {
+ if len(s) > 0 {
+ z := s[0]
+ s = s[1:]
+ return z, nil
+ }
+ return "", io.EOF
+ }
+ batch := NewBatch(scanner)
+ var batchResults []batchResult
+ for {
+ command, err := batch.Next()
+ if err != nil {
+ if err == io.EOF {
+ if v := batch.String(); v != "" {
+ // If meet the end of file, get the last batch.
+ batchResults = append(batchResults, batchResult{
+ Statements: batch.String(),
+ })
+ }
+ batch.Reset(nil)
+ return batchResults
+ }
+ a.NoError(err)
+ }
+ if command != nil {
+ batchResults = append(batchResults, batchResult{
+ Statements: batch.String(),
+ Command: command.String(),
+ })
+ batch.Reset(nil)
+ }
+ }
+}
diff --git a/backend/plugin/parser/tsql/batch/parse.go b/backend/plugin/parser/tsql/batch/parse.go
new file mode 100644
index 0000000000..91d5a1937f
--- /dev/null
+++ b/backend/plugin/parser/tsql/batch/parse.go
@@ -0,0 +1,48 @@
+package batch
+
+import "unicode"
+
+/*
+ * parse.go contains the logic of parsing a SQL batch.
+ * The original code can be found at https://sourcegraph.com/github.com/microsoft/go-sqlcmd@fb920dc0da056e58969696128b440e2bf99c105b/-/blob/pkg/sqlcmd/batch.go?L76-170.
+ */
+
+// grab grabs i from r, or returns 0 if 1 >= end.
+func grab(r []rune, i, end int) rune {
+ if i < end {
+ return r[i]
+ }
+ return 0
+}
+
+// readCommand reads to the next control character to find
+// a command in the string. Command regexes constrain matches
+// to the beginning of the string, and all commands consume
+// an entire line.
+func readCommand(r []rune, i, end int) (Command, int) {
+ for ; i < end; i++ {
+ next := grab(r, i, end)
+ if next == 0 || (unicode.IsControl(next) && next != '\t') {
+ break
+ }
+ }
+
+ for _, builder := range commandBuilders {
+ cmd := builder(string(r[:i]))
+ if cmd != nil {
+ return cmd, i
+ }
+ }
+ return nil, i
+}
+
+// readMultilineComment finds the end of a multiline comment (ie, '*/').
+func readMultilineComment(r []rune, i, end int) (int, bool) {
+ i++
+ for ; i < end; i++ {
+ if r[i-1] == '*' && r[i] == '/' {
+ return i, true
+ }
+ }
+ return end, false
+}
diff --git a/backend/plugin/parser/tsql/batch/testdata/test_batch.yaml b/backend/plugin/parser/tsql/batch/testdata/test_batch.yaml
new file mode 100644
index 0000000000..453e4bf30f
--- /dev/null
+++ b/backend/plugin/parser/tsql/batch/testdata/test_batch.yaml
@@ -0,0 +1,530 @@
+- input: |-
+ USE [smp_inv]
+ GO
+ /****** Object: StoredProcedure [dbo].[user_script_2] Script Date: 2023/11/30 17:27:18 ******/
+ SET ANSI_NULLS ON
+ GO
+ SET QUOTED_IDENTIFIER ON
+ GO
+ -- =============================================
+ -- Author: Bytebase
+ -- Create date: 2023-11-30
+ -- Description: Adjust
+ -- =============================================
+ CREATE PROCEDURE [dbo].[user_script_2]
+ @TenantCode VARCHAR(20),
+ @OrgId VARCHAR(10), -- Organization Id
+ -- @StoreCode VARCHAR(20), -- Store Code
+ -- @GoodsGid INT, -- Goods Id
+ @GoodsCode CHAR(8), -- 8-digit Goods Code
+ @BarCode VARCHAR(20), -- International Bar Code
+ @GoodsName VARCHAR(50), -- Goods Name
+ @SrcChannel VARCHAR(30), -- Source Channel
+ @BillType VARCHAR(10), -- Business Type
+ @BillNo VARCHAR(50), -- Bill Number
+ @BeginTime DATETIME, -- Start Time
+ @EndTime DATETIME, -- End Time
+ @Sorting VARCHAR(50), -- Sorting
+ @SkipCount INT, -- Skip Count
+ @MaxResultCount INT -- Maximum Result Count
+ AS
+ -- [Important] Template tags to generate dynamic scripts for different architectures
+ BEGIN
+ SET NOCOUNT ON;
+ DECLARE @bts BIGINT,
+ @ets BIGINT;
+ IF ISNULL(@BeginTime, '') <> ''
+ BEGIN
+ SET @bts = CONCAT(DATEDIFF(SS, '1970-1-1 00:00:00', @BeginTime), '000');
+ END;
+ IF ISNULL(@EndTime, '') <> ''
+ BEGIN
+ SET @ets = CONCAT(DATEDIFF(SS, '1970-1-1 00:00:00', @EndTime), '000');
+ END;
+ -- Bill types
+ IF OBJECT_ID('tempdb..#tp_bill_type') IS NOT NULL
+ DROP TABLE #tp_bill_type;
+ SELECT DISTINCT BillType,BillName INTO #tp_bill_type FROM t_cod_inv_bill_rule;
+ -- Output total count
+ SELECT COUNT(1)
+ FROM smp_his.dbo.t_log_inv_flow flw WITH (NOLOCK)
+ LEFT JOIN smp_mid..syst_smp_md_goods_basic_information_v1_0 md WITH (NOLOCK)
+ ON md.myj_goods_id = flw.GoodsGid
+ AND md.companycode=@TenantCode
+ WHERE flw.OrgId = @OrgId
+ AND flw.ChgOccQty <> 0
+ AND
+ (
+ ISNULL(@GoodsCode, '') = ''
+ OR flw.GoodsCode = @GoodsCode
+ )
+ AND
+ (
+ ISNULL(@BarCode, '') = ''
+ OR md.goods_common_code = @BarCode
+ )
+ AND
+ (
+ ISNULL(@GoodsName, '') = ''
+ OR md.myj_goods_chname LIKE CONCAT('%', @GoodsName, '%')
+ )
+ AND
+ (
+ ISNULL(@SrcChannel, '') = ''
+ OR flw.SrcChannel = @SrcChannel
+ )
+ AND
+ (
+ ISNULL(@BillType, '') = ''
+ OR flw.BillType = @BillType
+ )
+ AND
+ (
+ ISNULL(@BillNo, '') = ''
+ OR flw.BillNo = @BillNo
+ )
+ AND
+ (
+ @bts IS NULL
+ OR flw.OccurTime >= @bts
+ )
+ AND
+ (
+ @ets IS NULL
+ OR flw.OccurTime <= @ets
+ );
+ -- Output data
+ SELECT flw.OrgId,
+ flw.OrgCode,
+ flw.GoodsGid,
+ flw.GoodsCode,
+ md.goods_common_code AS BarCode,
+ md.myj_goods_chname AS GoodsName,
+ flw.BillType,
+ bt.BillName,
+ flw.BillNo,
+ CASE
+ WHEN flw.ChgOccQty > 0 THEN
+ 'Inbound (Increase Inventory)'
+ ELSE
+ 'Outbound (Decrease Inventory)'
+ END AS ChangeMsg,
+ flw.ChgOccQty AS ChangeQty,
+ flw.OccQtyBef AS QtyBef,
+ flw.OccQtyAft AS QtyAft,
+ flw.SrcChannel,
+ flw.Remark,
+ flw.Operator,
+ flw.OccurTime,
+ flw.CreationTime
+ FROM smp_his.dbo.t_log_inv_flow flw WITH (NOLOCK)
+ LEFT JOIN smp_mid..syst_smp_md_goods_basic_information_v1_0 md WITH (NOLOCK)
+ ON md.myj_goods_id = flw.GoodsGid
+ AND md.companycode=@TenantCode
+ INNER JOIN #tp_bill_type bt ON bt.BillType = flw.BillType
+ WHERE flw.OrgId = @OrgId
+ AND flw.ChgOccQty <> 0
+ AND
+ (
+ ISNULL(@GoodsCode, '') = ''
+ OR flw.GoodsCode = @GoodsCode
+ )
+ AND
+ (
+ ISNULL(@BarCode, '') = ''
+ OR md.goods_common_code = @BarCode
+ )
+ AND
+ (
+ ISNULL(@GoodsName, '') = ''
+ OR md.myj_goods_chname LIKE CONCAT('%', @GoodsName, '%')
+ )
+ AND
+ (
+ ISNULL(@SrcChannel, '') = ''
+ OR flw.SrcChannel = @SrcChannel
+ )
+ AND
+ (
+ ISNULL(@BillType, '') = ''
+ OR flw.BillType = @BillType
+ )
+ AND
+ (
+ ISNULL(@BillNo, '') = ''
+ OR flw.BillNo = @BillNo
+ )
+ AND
+ (
+ @bts IS NULL
+ OR flw.OccurTime >= @bts
+ )
+ AND
+ (
+ @ets IS NULL
+ OR flw.OccurTime <= @ets
+ )
+ ORDER BY flw.CreationTime DESC,
+ flw.OrgId,
+ flw.GoodsGid DESC OFFSET @SkipCount ROWS FETCH NEXT @MaxResultCount ROWS ONLY;
+ END;
+ GO
+ description: Sanitize user script#2
+ batches:
+ - statements: USE [smp_inv]
+ command: GO 1
+ - statements: |-
+ /****** Object: StoredProcedure [dbo].[user_script_2] Script Date: 2023/11/30 17:27:18 ******/
+ SET ANSI_NULLS ON
+ command: GO 1
+ - statements: SET QUOTED_IDENTIFIER ON
+ command: GO 1
+ - statements: |-
+ -- =============================================
+ -- Author: Bytebase
+ -- Create date: 2023-11-30
+ -- Description: Adjust
+ -- =============================================
+ CREATE PROCEDURE [dbo].[user_script_2]
+ @TenantCode VARCHAR(20),
+ @OrgId VARCHAR(10), -- Organization Id
+ -- @StoreCode VARCHAR(20), -- Store Code
+ -- @GoodsGid INT, -- Goods Id
+ @GoodsCode CHAR(8), -- 8-digit Goods Code
+ @BarCode VARCHAR(20), -- International Bar Code
+ @GoodsName VARCHAR(50), -- Goods Name
+ @SrcChannel VARCHAR(30), -- Source Channel
+ @BillType VARCHAR(10), -- Business Type
+ @BillNo VARCHAR(50), -- Bill Number
+ @BeginTime DATETIME, -- Start Time
+ @EndTime DATETIME, -- End Time
+ @Sorting VARCHAR(50), -- Sorting
+ @SkipCount INT, -- Skip Count
+ @MaxResultCount INT -- Maximum Result Count
+ AS
+ -- [Important] Template tags to generate dynamic scripts for different architectures
+ BEGIN
+ SET NOCOUNT ON;
+ DECLARE @bts BIGINT,
+ @ets BIGINT;
+ IF ISNULL(@BeginTime, '') <> ''
+ BEGIN
+ SET @bts = CONCAT(DATEDIFF(SS, '1970-1-1 00:00:00', @BeginTime), '000');
+ END;
+ IF ISNULL(@EndTime, '') <> ''
+ BEGIN
+ SET @ets = CONCAT(DATEDIFF(SS, '1970-1-1 00:00:00', @EndTime), '000');
+ END;
+ -- Bill types
+ IF OBJECT_ID('tempdb..#tp_bill_type') IS NOT NULL
+ DROP TABLE #tp_bill_type;
+ SELECT DISTINCT BillType,BillName INTO #tp_bill_type FROM t_cod_inv_bill_rule;
+ -- Output total count
+ SELECT COUNT(1)
+ FROM smp_his.dbo.t_log_inv_flow flw WITH (NOLOCK)
+ LEFT JOIN smp_mid..syst_smp_md_goods_basic_information_v1_0 md WITH (NOLOCK)
+ ON md.myj_goods_id = flw.GoodsGid
+ AND md.companycode=@TenantCode
+ WHERE flw.OrgId = @OrgId
+ AND flw.ChgOccQty <> 0
+ AND
+ (
+ ISNULL(@GoodsCode, '') = ''
+ OR flw.GoodsCode = @GoodsCode
+ )
+ AND
+ (
+ ISNULL(@BarCode, '') = ''
+ OR md.goods_common_code = @BarCode
+ )
+ AND
+ (
+ ISNULL(@GoodsName, '') = ''
+ OR md.myj_goods_chname LIKE CONCAT('%', @GoodsName, '%')
+ )
+ AND
+ (
+ ISNULL(@SrcChannel, '') = ''
+ OR flw.SrcChannel = @SrcChannel
+ )
+ AND
+ (
+ ISNULL(@BillType, '') = ''
+ OR flw.BillType = @BillType
+ )
+ AND
+ (
+ ISNULL(@BillNo, '') = ''
+ OR flw.BillNo = @BillNo
+ )
+ AND
+ (
+ @bts IS NULL
+ OR flw.OccurTime >= @bts
+ )
+ AND
+ (
+ @ets IS NULL
+ OR flw.OccurTime <= @ets
+ );
+ -- Output data
+ SELECT flw.OrgId,
+ flw.OrgCode,
+ flw.GoodsGid,
+ flw.GoodsCode,
+ md.goods_common_code AS BarCode,
+ md.myj_goods_chname AS GoodsName,
+ flw.BillType,
+ bt.BillName,
+ flw.BillNo,
+ CASE
+ WHEN flw.ChgOccQty > 0 THEN
+ 'Inbound (Increase Inventory)'
+ ELSE
+ 'Outbound (Decrease Inventory)'
+ END AS ChangeMsg,
+ flw.ChgOccQty AS ChangeQty,
+ flw.OccQtyBef AS QtyBef,
+ flw.OccQtyAft AS QtyAft,
+ flw.SrcChannel,
+ flw.Remark,
+ flw.Operator,
+ flw.OccurTime,
+ flw.CreationTime
+ FROM smp_his.dbo.t_log_inv_flow flw WITH (NOLOCK)
+ LEFT JOIN smp_mid..syst_smp_md_goods_basic_information_v1_0 md WITH (NOLOCK)
+ ON md.myj_goods_id = flw.GoodsGid
+ AND md.companycode=@TenantCode
+ INNER JOIN #tp_bill_type bt ON bt.BillType = flw.BillType
+ WHERE flw.OrgId = @OrgId
+ AND flw.ChgOccQty <> 0
+ AND
+ (
+ ISNULL(@GoodsCode, '') = ''
+ OR flw.GoodsCode = @GoodsCode
+ )
+ AND
+ (
+ ISNULL(@BarCode, '') = ''
+ OR md.goods_common_code = @BarCode
+ )
+ AND
+ (
+ ISNULL(@GoodsName, '') = ''
+ OR md.myj_goods_chname LIKE CONCAT('%', @GoodsName, '%')
+ )
+ AND
+ (
+ ISNULL(@SrcChannel, '') = ''
+ OR flw.SrcChannel = @SrcChannel
+ )
+ AND
+ (
+ ISNULL(@BillType, '') = ''
+ OR flw.BillType = @BillType
+ )
+ AND
+ (
+ ISNULL(@BillNo, '') = ''
+ OR flw.BillNo = @BillNo
+ )
+ AND
+ (
+ @bts IS NULL
+ OR flw.OccurTime >= @bts
+ )
+ AND
+ (
+ @ets IS NULL
+ OR flw.OccurTime <= @ets
+ )
+ ORDER BY flw.CreationTime DESC,
+ flw.OrgId,
+ flw.GoodsGid DESC OFFSET @SkipCount ROWS FETCH NEXT @MaxResultCount ROWS ONLY;
+ END;
+ command: GO 1
+- input: |-
+ USE [run]
+ GO
+
+ SET ANSI_NULLS ON
+ GO
+ SET QUOTED_IDENTIFIER OFF
+ GO
+
+ if exists(select * from sys.objects where name = 'user_proc_01')
+ drop proc user_proc_01
+ go
+
+ CREATE proc [dbo].[user_proc_01]
+ @p_orgid dtorgid,
+ @p_custid dtcustid,
+ @p_flag dtkind
+ as
+
+ declare @serverid dtsno, @sysdate dtdate,@p_qsdm dtchar255
+ declare @money_rmb dtkind, @money_hk dtkind
+
+ select @money_rmb = dbo.convertmoneytype('RMB') --0
+ select @money_hk = dbo.convertmoneytype('HK') --1
+ declare @szAmarket dtkind,@szBmarket dtkind,@thirdAmarket dtkind, @thirdBmarket dtkind,@HGTmarket dtkind,@shBmarket dtkind
+ select @szAmarket = dbo.convertmarket('SZAG') --0
+ select @szBmarket = dbo.convertmarket('SZBG') --2
+ select @shBmarket = dbo.convertmarket('SHBG') --3
+ select @thirdAmarket = dbo.convertmarket('ZRA') --6
+ select @thirdBmarket = dbo.convertmarket('ZRB') --7
+ select @HGTmarket = dbo.convertmarket('HGT') --5
+ select @serverid = 0
+ select top 1 @sysdate = sysdate,@serverid = serverid from sysconfig
+ select @p_qsdm = paravalue from dbo.mixedconfig where paraid = 'oes_zqgsdm_zy'
+ select errorcode = 0 , errormsg = 'Success'
+
+ begin
+ select sum(cn.num) as num from(
+ select count(1) as num
+ from dbo.logasset a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.serverid = @serverid and a.digestid in (220000,221001)
+ and a.bizdate = @sysdate and a.orgid = @p_orgid and a.custid = @p_custid
+ union all
+ select count(1) as num
+ from dbo.logmateno a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.serverid = @serverid and a.bizdate = @sysdate and a.orgid = @p_orgid and a.custid = @p_custid
+ union all
+ select count(1) as num
+ from dbo.logasset a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.digestid in(221008,221009,250163)
+ and a.bizdate = @sysdate and a.serverid = @serverid
+ and a.orgid = @p_orgid and a.custid = @p_custid) cn
+
+
+ end
+ return 0
+
+ GO
+ description: Sanitize user script#1
+ batches:
+ - statements: USE [run]
+ command: GO 1
+ - statements: |2-
+
+ SET ANSI_NULLS ON
+ command: GO 1
+ - statements: SET QUOTED_IDENTIFIER OFF
+ command: GO 1
+ - statements: |2-
+
+ if exists(select * from sys.objects where name = 'user_proc_01')
+ drop proc user_proc_01
+ command: GO 1
+ - statements: |2
+
+ CREATE proc [dbo].[user_proc_01]
+ @p_orgid dtorgid,
+ @p_custid dtcustid,
+ @p_flag dtkind
+ as
+
+ declare @serverid dtsno, @sysdate dtdate,@p_qsdm dtchar255
+ declare @money_rmb dtkind, @money_hk dtkind
+
+ select @money_rmb = dbo.convertmoneytype('RMB') --0
+ select @money_hk = dbo.convertmoneytype('HK') --1
+ declare @szAmarket dtkind,@szBmarket dtkind,@thirdAmarket dtkind, @thirdBmarket dtkind,@HGTmarket dtkind,@shBmarket dtkind
+ select @szAmarket = dbo.convertmarket('SZAG') --0
+ select @szBmarket = dbo.convertmarket('SZBG') --2
+ select @shBmarket = dbo.convertmarket('SHBG') --3
+ select @thirdAmarket = dbo.convertmarket('ZRA') --6
+ select @thirdBmarket = dbo.convertmarket('ZRB') --7
+ select @HGTmarket = dbo.convertmarket('HGT') --5
+ select @serverid = 0
+ select top 1 @sysdate = sysdate,@serverid = serverid from sysconfig
+ select @p_qsdm = paravalue from dbo.mixedconfig where paraid = 'oes_zqgsdm_zy'
+ select errorcode = 0 , errormsg = 'Success'
+
+ begin
+ select sum(cn.num) as num from(
+ select count(1) as num
+ from dbo.logasset a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.serverid = @serverid and a.digestid in (220000,221001)
+ and a.bizdate = @sysdate and a.orgid = @p_orgid and a.custid = @p_custid
+ union all
+ select count(1) as num
+ from dbo.logmateno a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.serverid = @serverid and a.bizdate = @sysdate and a.orgid = @p_orgid and a.custid = @p_custid
+ union all
+ select count(1) as num
+ from dbo.logasset a
+ inner join dbo.custbaseinfo c on a.custid = c.custid and a.serverid = c.serverid
+ where a.digestid in(221008,221009,250163)
+ and a.bizdate = @sysdate and a.serverid = @serverid
+ and a.orgid = @p_orgid and a.custid = @p_custid) cn
+
+
+ end
+ return 0
+ command: GO 1
+- input: |-
+ INSERT INTO T VALUES ('
+ Bytebase Inc.
+ ');
+ description: Cross line string using `'` as quote.
+ batches:
+ - statements: |-
+ INSERT INTO T VALUES ('
+ Bytebase Inc.
+ ');
+ command: ""
+- input: |-
+ SELECT * FROM T;
+ GO
+ INSERT INTO T VALUES (1);
+ GO
+ description: Multiple batches
+ batches:
+ - statements: SELECT * FROM T;
+ command: GO 1
+ - statements: INSERT INTO T VALUES (1);
+ command: GO 1
+- input: |-
+ /*
+ * Bytebase Inc.
+ * Migration SQL File 2023/11/30
+ * INSERT INTO XXX VALUES (1);
+ */
+ INSERT INTO T VALUES (1);
+ description: Multi-line comment
+ batches:
+ - statements: |-
+ /*
+ * Bytebase Inc.
+ * Migration SQL File 2023/11/30
+ * INSERT INTO XXX VALUES (1);
+ */
+ INSERT INTO T VALUES (1);
+ command: ""
+- input: |-
+ -- Migration SQL File 2023/11/30
+ INSERT INTO T VALUES (1);
+ description: ""
+ batches:
+ - statements: |-
+ -- Migration SQL File 2023/11/30
+ INSERT INTO T VALUES (1);
+ command: ""
+- input: |-
+ SELECT * FROM T;
+ GO 2
+ description: Run a batch twice
+ batches:
+ - statements: SELECT * FROM T;
+ command: GO 2
+- input: SELECT * FROM T;
+ description: Simple statement
+ batches:
+ - statements: SELECT * FROM T;
+ command: ""