{"id":50717144,"url":"https://github.com/renaldid/n1detect","last_synced_at":"2026-06-09T19:30:36.354Z","repository":{"id":361118746,"uuid":"1235125175","full_name":"renaldid/n1detect","owner":"renaldid","description":"Go static analysis tool that detects N+1 database query patterns in for/range loops","archived":false,"fork":false,"pushed_at":"2026-05-11T03:24:00.000Z","size":12,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-29T09:34:31.742Z","etag":null,"topics":["database","go","go-vet","golang","golangci-lint","gorm","linter","n-plus-one","performance","pgx","query-optimization","sqlx","static-analysis"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/renaldid.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-11T03:12:32.000Z","updated_at":"2026-05-11T03:24:02.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/renaldid/n1detect","commit_stats":null,"previous_names":["renaldid/n1detect"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/renaldid/n1detect","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/renaldid%2Fn1detect","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/renaldid%2Fn1detect/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/renaldid%2Fn1detect/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/renaldid%2Fn1detect/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/renaldid","download_url":"https://codeload.github.com/renaldid/n1detect/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/renaldid%2Fn1detect/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34123169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-09T02:00:06.510Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","go","go-vet","golang","golangci-lint","gorm","linter","n-plus-one","performance","pgx","query-optimization","sqlx","static-analysis"],"created_at":"2026-06-09T19:30:34.537Z","updated_at":"2026-06-09T19:30:36.349Z","avatar_url":"https://github.com/renaldid.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# n1detect\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/renaldid/n1detect.svg)](https://pkg.go.dev/github.com/renaldid/n1detect)\n[![Go Version](https://img.shields.io/badge/go-%3E%3D1.22-blue)](https://golang.org/dl/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n[![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/renaldid/n1detect)\n\n**n1detect** is a Go static analysis tool that detects **N+1 database query patterns** — one of the most common and costly performance bugs in database-driven applications.\n\nIt integrates with `go vet`, `golangci-lint`, and any tool built on the [`go/analysis`](https://pkg.go.dev/golang.org/x/tools/go/analysis) framework.\n\n---\n\n## What is an N+1 Query?\n\nAn N+1 query happens when you fetch a list of N records and then issue one additional query **per record** inside a loop:\n\n```go\n// 1 query to get all user IDs\nrows, _ := db.Query(\"SELECT id FROM users\")\nfor rows.Next() {\n    var id int\n    rows.Scan(\u0026id)\n    // N queries — one per user!  \u003c-- n1detect flags this\n    db.QueryRow(\"SELECT * FROM orders WHERE user_id = ?\", id)\n}\n```\n\nThis pattern produces **N+1 round-trips** to the database. With 1,000 users that's 1,001 queries instead of 1. Under load it becomes the primary source of database saturation, high latency, and connection pool exhaustion.\n\n### Fix: batch with JOIN or IN\n\n```go\n// 1 query — always, regardless of user count\ndb.Query(`\n    SELECT u.id, o.id, o.total\n    FROM users u\n    JOIN orders o ON o.user_id = u.id\n`)\n\n// or with an IN clause\ndb.Query(\"SELECT * FROM orders WHERE user_id IN (?)\", userIDs)\n```\n\n---\n\n## Installation\n\n### Standalone CLI\n\n```bash\ngo install github.com/renaldid/n1detect/cmd/n1detect@latest\n```\n\nRun on a module:\n\n```bash\nn1detect ./...\n```\n\n### As a `go vet` plugin\n\n```bash\ngo vet -vettool=$(which n1detect) ./...\n```\n\n### With `golangci-lint` (custom linter)\n\nAdd to `.golangci.yml`:\n\n```yaml\nlinters-settings:\n  custom:\n    n1detect:\n      path: n1detect\n      description: Detects N+1 database query patterns\n      original-url: github.com/renaldid/n1detect\n```\n\n---\n\n## Supported libraries\n\nn1detect detects N+1 patterns across all major Go database libraries out of the box:\n\n| Library | Detected types | Detected methods |\n|---------|----------------|-----------------|\n| `database/sql` | `DB`, `Tx`, `Conn` | `Query`, `QueryRow`, `QueryContext`, `QueryRowContext`, `Exec`, `ExecContext`, `Prepare`, `PrepareContext` |\n| `gorm.io/gorm` | `DB` | `Find`, `First`, `Last`, `Take`, `Create`, `Save`, `Delete`, `Updates`, `Update`, `Scan`, `Row`, `Rows`, `Exec` |\n| `github.com/jackc/pgx/v5` | `Conn` | `Query`, `QueryRow`, `Exec`, `SendBatch` |\n| `github.com/jackc/pgx/v5/pgxpool` | `Pool` | `Query`, `QueryRow`, `Exec`, `SendBatch` |\n| `github.com/jmoiron/sqlx` | `DB`, `Tx` | `Query`, `QueryRow`, `QueryContext`, `QueryRowContext`, `Exec`, `ExecContext`, `Select`, `SelectContext`, `Get`, `GetContext` |\n\n---\n\n## Example output\n\n```\n./service/user.go:42:3: potential N+1 query: DB.QueryRow called inside loop; consider batching or using JOIN\n./repository/post.go:18:4: potential N+1 query: DB.Query called inside loop; consider batching or using JOIN\n./store/order.go:31:3: potential N+1 query: Tx.Exec called inside loop; consider batching or using JOIN\n```\n\n---\n\n## Detected patterns\n\n### For loop\n\n```go\nfunc loadTags(db *sql.DB, postIDs []int) {\n    for _, id := range postIDs {\n        db.Query(\"SELECT * FROM tags WHERE post_id = ?\", id) // flagged\n    }\n}\n```\n\n### Range loop\n\n```go\nfunc deletePosts(tx *sql.Tx, ids []int) {\n    for _, id := range ids {\n        tx.Exec(\"DELETE FROM posts WHERE id = ?\", id) // flagged\n    }\n}\n```\n\n### GORM\n\n```go\nfunc loadUserProfiles(db *gorm.DB, users []User) {\n    for _, u := range users {\n        var profile Profile\n        db.First(\u0026profile, \"user_id = ?\", u.ID) // flagged\n    }\n}\n```\n\n### Function literal in loop\n\n```go\nfor _, id := range ids {\n    go func() {\n        db.QueryRow(\"SELECT * FROM t WHERE id = ?\", id) // flagged\n    }()\n}\n```\n\n### Nested loops\n\n```go\nfor _, dept := range departments {\n    for _, emp := range dept.Employees {\n        db.Query(\"SELECT * FROM salaries WHERE employee_id = ?\", emp.ID) // flagged\n    }\n}\n```\n\n---\n\n## Custom patterns\n\nRegister your own database types and methods using `WithPatterns`:\n\n```go\nimport \"github.com/renaldid/n1detect\"\n\nvar myAnalyzer = n1detect.WithPatterns(\n    n1detect.Pattern{\n        PkgPath:  \"github.com/myorg/mydb\",\n        TypeName: \"Client\",\n        Methods:  []string{\"Find\", \"Query\", \"Exec\"},\n    },\n)\n```\n\nUse it with `multichecker`:\n\n```go\npackage main\n\nimport (\n    \"golang.org/x/tools/go/analysis/multichecker\"\n    \"github.com/renaldid/n1detect\"\n)\n\nfunc main() {\n    multichecker.Main(\n        n1detect.WithPatterns(/* your patterns */),\n    )\n}\n```\n\n---\n\n## Programmatic API\n\n```go\nimport \"github.com/renaldid/n1detect\"\n\n// Use the default analyzer (all built-in patterns)\nvar Analyzer = n1detect.Analyzer\n\n// Extend with custom patterns\nvar Extended = n1detect.WithPatterns(\n    n1detect.Pattern{\n        PkgPath:  \"github.com/myorg/cache\",\n        TypeName: \"DB\",\n        Methods:  []string{\"Get\", \"Set\"},\n    },\n)\n```\n\n`n1detect.Analyzer` implements [`analysis.Analyzer`](https://pkg.go.dev/golang.org/x/tools/go/analysis#Analyzer) and works with any tool in the `go/analysis` ecosystem.\n\n---\n\n## How it works\n\nn1detect uses Go's type-checker — not string matching — to identify database calls:\n\n1. For each `for` or `range` loop in the AST, it collects all call expressions within the loop body.\n2. Each call is type-checked: the receiver's concrete type (e.g. `*sql.DB`) is resolved via `go/types`.\n3. The resolved type is matched against the pattern registry (`PkgPath + TypeName + MethodName`).\n4. A diagnostic is reported at the call site.\n\nBecause analysis is **type-aware**, there are no false positives from unrelated types that happen to share a method name (e.g. a custom `Query()` on your own struct).\n\n**Known limitation:** interprocedural N+1 patterns (where the DB call is inside a helper function called from the loop) are not detected in v1. Only direct calls inside loop bodies are flagged.\n\n---\n\n## False positives\n\nn1detect only flags calls where **the receiver is a known database type**. These patterns are intentionally not flagged:\n\n```go\n// Interface type — receiver is unknown at compile time\nvar q Querier\nfor _, id := range ids {\n    q.Query(id) // NOT flagged\n}\n\n// Batch query outside loop — safe\ndb.Query(\"SELECT * FROM users WHERE id IN (?)\", ids) // NOT flagged\n\n// Custom struct with same method name\ntype MyService struct{}\nfunc (s MyService) Query() {}\n\nfor range items {\n    s.Query() // NOT flagged — MyService is not a registered DB type\n}\n```\n\n---\n\n## Contributing\n\nIssues and pull requests are welcome. Please open an issue before submitting large changes.\n\n---\n\n## License\n\n[MIT](LICENSE)\n\n---\n\n\u003c!-- SEO keywords: golang n+1 query, go n+1 database, detect n+1 golang, n+1 problem go, golang database performance, n+1 query linter go, go vet n+1, golangci-lint n+1, gorm n+1 queries, database/sql n+1, go sql loop query, n+1 query static analysis golang, golang query inside loop, go database anti-pattern, n+1 detection tool go, golang orm n+1, fix n+1 queries go, n plus one query golang --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frenaldid%2Fn1detect","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frenaldid%2Fn1detect","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frenaldid%2Fn1detect/lists"}