Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: use WITH clause with a limit to query (#2892)
Danny Xu70c1b3fcf4cc
diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex ce6f3a4ca3..385f4933c6 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -306,6 +306,9 @@ func EndMigration(ctx context.Context, executor MigrationExecutor, startedNs int// Query will execute a readonly / SELECT query.func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string, limit int) ([]interface{}, error) {+ // Limit SQL query result size.+ statement = getStatementWithResultLimit(statement, limit)+// Not all sql engines support ReadOnly flag, so we will use tx rollback semantics to enforce readonly.readOnly := true// TiDB doesn't support READ ONLY transactions. We have to skip the flag for it.@@ -344,7 +347,6 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,columnTypeNames = append(columnTypeNames, strings.ToUpper(v.DatabaseTypeName()))}- rowCount := 0data := []interface{}{}for rows.Next() {scanArgs := make([]interface{}, colCount)@@ -395,10 +397,6 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,}data = append(data, rowData)- rowCount++- if rowCount == limit {- break- }}if err := rows.Err(); err != nil {return nil, err@@ -407,6 +405,18 @@ func Query(ctx context.Context, dbType db.Type, sqldb *sql.DB, statement string,return []interface{}{columnNames, columnTypeNames, data}, nil}+func getStatementWithResultLimit(stmt string, limit int) string {+ stmt = strings.TrimRight(stmt, " \n\t;")+ if !strings.HasPrefix(stmt, "EXPLAIN") {+ limitPart := ""+ if limit > 0 {+ limitPart = fmt.Sprintf(" LIMIT %d", limit)+ }+ return fmt.Sprintf("WITH result AS (%s) SELECT * FROM result%s;", stmt, limitPart)+ }+ return stmt+}+// FindMigrationHistoryList will find the list of migration history.func FindMigrationHistoryList(ctx context.Context, findMigrationHistoryListQuery string, queryParams []interface{}, driver db.Driver, database string) ([]*db.MigrationHistory, error) {// To support `pg` option, the util layer will not know which database where `migration_history` table is,diff --git a/plugin/db/util/driverutil_test.go b/plugin/db/util/driverutil_test.goindex 5afd5e4eab..2d8f075cfa 100644--- a/plugin/db/util/driverutil_test.go+++ b/plugin/db/util/driverutil_test.go@@ -68,3 +68,54 @@ func TestFromStoredVersion(t *testing.T) {require.Equal(t, tc.wantSemanticVersionSuffix, gotSemanticVersionSuffix)}}++func TestGetStatementWithResultLimit(t *testing.T) {+ tests := []struct {+ sqlStatement string+ limit int+ want string+ }{+ {+ sqlStatement: " seLeCT * FROM test;",+ limit: 123,+ want: "WITH result AS ( seLeCT * FROM test) SELECT * FROM result LIMIT 123;",+ },+ {+ sqlStatement: " seLeCT * FROM test;",+ limit: 0,+ want: "WITH result AS ( seLeCT * FROM test) SELECT * FROM result;",+ },+ {+ sqlStatement: " \n \r SELEct * from test ",+ limit: 100,+ want: "WITH result AS ( \n \r SELEct * from test) SELECT * FROM result LIMIT 100;",+ },+ {+ sqlStatement: "SELECT\n*\nFROM\ntest ;\n",+ limit: 100,+ want: "WITH result AS (SELECT\n*\nFROM\ntest) SELECT * FROM result LIMIT 100;",+ },+ {+ sqlStatement: "SELECT\n*\nFROM\ntest ;;;\n",+ limit: 100,+ want: "WITH result AS (SELECT\n*\nFROM\ntest) SELECT * FROM result LIMIT 100;",+ },+ {+ sqlStatement: "SELECT\n*\nFROM\n`test;` ;;;\n",+ limit: 100,+ want: "WITH result AS (SELECT\n*\nFROM\n`test;`) SELECT * FROM result LIMIT 100;",+ },+ {+ sqlStatement: "EXPLAIN \n \r SELEct * from test ",+ limit: 0,+ want: "EXPLAIN \n \r SELEct * from test",+ },+ }++ for _, test := range tests {+ got := getStatementWithResultLimit(test.sqlStatement, test.limit)+ if got != test.want {+ t.Errorf("trimSQLStatement %q: got result %v, want %v.", test.sqlStatement, got, test.want)+ }+ }+}diff --git a/server/sql.go b/server/sql.goindex 05d57f8823..20b5442e03 100644--- a/server/sql.go+++ b/server/sql.go@@ -316,9 +316,8 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {resultSet := &api.SQLResultSet{AdviceList: adviceList}if queryErr == nil {resultSet.Data = string(bytes)- log.Debug("Query result",+ log.Debug("Query result advice",zap.String("statement", exec.Statement),- zap.String("data", resultSet.Data),zap.Array("advice", advisor.ZapAdviceArray(resultSet.AdviceList)),)} else {