(sql string, stmt *ast.SelectStmt, limitCount int)
| 188 | } |
| 189 | |
| 190 | func rewriteMySQLSelectLimit(sql string, stmt *ast.SelectStmt, limitCount int) (string, error) { |
| 191 | if stmt.Limit != nil && stmt.Limit.Count != nil { |
| 192 | existingLimit := extractMySQLLimit(stmt.Limit.Count) |
| 193 | if existingLimit >= 0 && existingLimit <= limitCount { |
| 194 | return sql, nil |
| 195 | } |
| 196 | loc := nodeLocOf(stmt.Limit.Count) |
| 197 | loc = trimMySQLLocSpace(sql, loc) |
| 198 | if loc.Start >= 0 && loc.End > loc.Start && loc.End <= len(sql) { |
| 199 | if existingLimit < 0 && stmt.Into == nil { |
| 200 | return "", errors.Errorf("cannot rewrite non-constant LIMIT expression") |
| 201 | } |
| 202 | return sql[:loc.Start] + fmt.Sprintf("%d", limitCount) + sql[loc.End:], nil |
| 203 | } |
| 204 | return "", errors.Errorf("cannot rewrite non-constant LIMIT expression") |
| 205 | } |
| 206 | |
| 207 | insertPos, beforeClause := findMySQLLimitInsertPosition(sql, stmt) |
| 208 | if insertPos < 0 || insertPos > len(sql) { |
| 209 | return "", errors.Errorf("invalid LIMIT insert position %d", insertPos) |
| 210 | } |
| 211 | if beforeClause { |
| 212 | return sql[:insertPos] + fmt.Sprintf("LIMIT %d ", limitCount) + sql[insertPos:], nil |
| 213 | } |
| 214 | return sql[:insertPos] + fmt.Sprintf(" LIMIT %d", limitCount) + sql[insertPos:], nil |
| 215 | } |
| 216 | |
| 217 | func findMySQLLimitInsertPosition(sql string, stmt *ast.SelectStmt) (int, bool) { |
| 218 | if stmt.Into != nil && stmt.Into.Loc.Start > 0 { |
no test coverage detected