|
1 | 1 | package database
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "regexp" |
| 5 | + "strings" |
4 | 6 | "testing"
|
5 | 7 | "time"
|
6 | 8 |
|
| 9 | + "github.com/google/go-cmp/cmp" |
7 | 10 | "github.com/stretchr/testify/require"
|
8 | 11 |
|
9 | 12 | "github.com/coder/coder/v2/testutil"
|
@@ -54,3 +57,41 @@ func TestWorkspaceTableConvert(t *testing.T) {
|
54 | 57 | "'workspace.WorkspaceTable()' is not missing at least 1 field when converting to 'WorkspaceTable'. "+
|
55 | 58 | "To resolve this, go to the 'func (w Workspace) WorkspaceTable()' and ensure all fields are converted.")
|
56 | 59 | }
|
| 60 | + |
| 61 | +// TestAuditLogsQueryConsistency ensures that GetAuditLogsOffset and CountAuditLogs |
| 62 | +// have identical WHERE clauses to prevent filtering inconsistencies. |
| 63 | +// This test is a guard rail to prevent developer oversight mistakes. |
| 64 | +func TestAuditLogsQueryConsistency(t *testing.T) { |
| 65 | + t.Parallel() |
| 66 | + |
| 67 | + getWhereClause := extractWhereClause(getAuditLogsOffset) |
| 68 | + require.NotEmpty(t, getWhereClause, "failed to extract WHERE clause from GetAuditLogsOffset") |
| 69 | + |
| 70 | + countWhereClause := extractWhereClause(countAuditLogs) |
| 71 | + require.NotEmpty(t, countWhereClause, "failed to extract WHERE clause from CountAuditLogs") |
| 72 | + |
| 73 | + // Compare the WHERE clauses |
| 74 | + if diff := cmp.Diff(getWhereClause, countWhereClause); diff != "" { |
| 75 | + t.Errorf("GetAuditLogsOffset and CountAuditLogs WHERE clauses must be identical to ensure consistent filtering.\nDiff:\n%s", diff) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +// extractWhereClause extracts the WHERE clause from a SQL query string |
| 80 | +func extractWhereClause(query string) string { |
| 81 | + // Find WHERE and get everything after it |
| 82 | + wherePattern := regexp.MustCompile(`(?is)WHERE\s+(.*)`) |
| 83 | + whereMatches := wherePattern.FindStringSubmatch(query) |
| 84 | + if len(whereMatches) < 2 { |
| 85 | + return "" |
| 86 | + } |
| 87 | + |
| 88 | + whereClause := whereMatches[1] |
| 89 | + |
| 90 | + // Remove ORDER BY, LIMIT, OFFSET clauses from the end |
| 91 | + whereClause = regexp.MustCompile(`(?is)\s+(ORDER BY|LIMIT|OFFSET).*$`).ReplaceAllString(whereClause, "") |
| 92 | + |
| 93 | + // Remove SQL comments |
| 94 | + whereClause = regexp.MustCompile(`(?m)--.*$`).ReplaceAllString(whereClause, "") |
| 95 | + |
| 96 | + return strings.TrimSpace(whereClause) |
| 97 | +} |
0 commit comments