{"id":20433116,"url":"https://github.com/sivaosorg/qb","last_synced_at":"2026-05-05T01:35:38.018Z","repository":{"id":214277433,"uuid":"695849975","full_name":"sivaosorg/qb","owner":"sivaosorg","description":"QueryBuilder is a powerful and flexible Go library for building SQL queries with ease. It simplifies the process of constructing SQL statements, making it effortless to interact with your database.","archived":false,"fork":false,"pushed_at":"2024-09-07T05:24:11.000Z","size":45,"stargazers_count":0,"open_issues_count":4,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-26T19:02:06.300Z","etag":null,"topics":["go-query","golang","mysql","mysql-database","native-sql-engine","postgresql","postgresql-database","postrges","query-builder","query-sql","sql","sql-builder","sqlx"],"latest_commit_sha":null,"homepage":"https://github.com/sivaosorg/qb","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sivaosorg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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}},"created_at":"2023-09-24T12:26:18.000Z","updated_at":"2024-09-07T05:24:14.000Z","dependencies_parsed_at":"2024-09-07T06:41:32.725Z","dependency_job_id":null,"html_url":"https://github.com/sivaosorg/qb","commit_stats":null,"previous_names":["sivaosorg/qb"],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/sivaosorg/qb","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sivaosorg%2Fqb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sivaosorg%2Fqb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sivaosorg%2Fqb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sivaosorg%2Fqb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sivaosorg","download_url":"https://codeload.github.com/sivaosorg/qb/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sivaosorg%2Fqb/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32632288,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-04T10:08:07.713Z","status":"ssl_error","status_checked_at":"2026-05-04T10:08:02.005Z","response_time":58,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["go-query","golang","mysql","mysql-database","native-sql-engine","postgresql","postgresql-database","postrges","query-builder","query-sql","sql","sql-builder","sqlx"],"created_at":"2024-11-15T08:17:47.630Z","updated_at":"2026-05-05T01:35:37.981Z","avatar_url":"https://github.com/sivaosorg.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# QueryBuilder - qb\n\n---\n\nQueryBuilder is a powerful and flexible Go library for building SQL queries with ease. It simplifies the process of constructing SQL statements, making it effortless to interact with your database.\n\n## Features\n\n- SELECT Queries: Construct complex SELECT queries with dynamic columns, conditions, and JOIN operations.\n- UPDATE Queries: Build UPDATE statements to modify database records with ease.\n- DELETE Queries: Easily create DELETE statements to remove data from your tables.\n- JSON/JSONB Support: Seamlessly handle JSON and JSONB data types in your queries.\n- JOIN Operations: Perform INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN operations with JSON/JSONB columns.\n- Parameterized Queries: Safely construct parameterized queries to prevent SQL injection.\n\u003c!-- - Alias Support: Assign aliases to tables for more readable and maintainable queries. --\u003e\n\n## Installation\n\n```bash\ngo get -u github.com/sivaosorg/qb\n```\n\n## Table of Contents\n\n- [QueryBuilder - qb](#querybuilder---qb)\n  - [Features](#features)\n  - [Installation](#installation)\n  - [Table of Contents](#table-of-contents)\n    - [Selects, Ordering, Limit and Offset](#selects-ordering-limit-and-offset)\n    - [GroupBy / Having](#groupby--having)\n    - [Where, AndWhere and OrWhere clauses](#where-andwhere-and-orwhere-clauses)\n    - [WhereIn and WhereNotIn clauses](#wherein-and-wherenotin-clauses)\n    - [WhereNull and WhereNotNull clauses](#wherenull-and-wherenotnull-clauses)\n    - [WhereExists and WhereNotExists clauses](#whereexists-and-wherenotexists-clauses)\n    - [WhereBetween and WhereNotBetween clauses](#wherebetween-and-wherenotbetween-clauses)\n    - [Left / Right / Inner / Left Outer Joins](#left--right--inner--left-outer-joins)\n    - [Insert](#insert)\n    - [Update](#update)\n    - [Drop, Truncate and Rename](#drop-truncate-and-rename)\n    - [Increment and Decrement](#increment-and-decrement)\n    - [Union and Union All](#union-and-union-all)\n    - [Transaction Mode](#transaction-mode)\n    - [Aggregates](#aggregates)\n    - [Create Table](#create-table)\n    - [Add / Modify / Drop columns](#add--modify--drop-columns)\n    - [Chunk](#chunk)\n  - [Ref](#ref)\n  - [Contribution](#contribution)\n\n### Selects, Ordering, Limit and Offset\n\nYou might not always need to retrieve all columns from a database table. With the select method, you have the flexibility to define a custom select clause for your query:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=database_username dbname=database_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest01()\n}\n\nfunc test01() {\n\tquery := db.\n\t\tTable(\"or_user\").\n\t\tSelect(\"or_user.user_id, or_user.user_name, or_user.phone , or_user.modifydate\")\n\n\tresult, err := query.OrderBy(\"or_user.user_id\", \"DESC\").Limit(5).Offset(0).Get()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tquery.PrintQuery()\n\tfor k, v := range result {\n\t\tfor field, value := range v {\n\t\t\tlog.Println(fmt.Sprintf(\"key = %v =\u003e field = %v, value = %v\", k, field, value))\n\t\t}\n\t}\n}\n```\n\n### GroupBy / Having\n\nThe GroupBy and Having methods may be used to group the query results.\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest02()\n}\n\nfunc test02() {\n\tquery := db.\n\t\tTable(\"or_user\").\n\t\tSelect(\"or_user.user_id, or_user.user_name, or_user.phone , or_user.modifydate\")\n\n\tresult, err := query.GroupBy(\"or_user.user_id\").Having(\"or_user.user_id\", \"\u003e\", 1).Get()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tquery.PrintQuery()\n\tfor k, v := range result {\n\t\tfor field, value := range v {\n\t\t\tlog.Println(fmt.Sprintf(\"key = %v =\u003e field = %v, value = %v\", k, field, value))\n\t\t}\n\t}\n}\n```\n\n### Where, AndWhere and OrWhere clauses\n\nThe simplest form of the \"where\" function necessitates three arguments. The initial argument designates the column name, followed by the second argument, which specifies an operator drawn from the set of supported operators within the database. Last but not least, the third argument entails the value against which the column is to be evaluated.\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest03()\n}\n\nfunc test03() {\n\tquery := db.\n\t\tTable(\"or_user\").\n\t\tSelect(\"or_user.user_id, or_user.user_name, or_user.phone , or_user.modifydate\")\n\n\tquery = query.Where(\"or_user.user_id\", \"=\", 611235).\n\t\tAndWhere(\"or_user_role.user_id\", \"=\", 611235)\n\n\tresult, err := query.OrderBy(\"or_user.user_id\", \"DESC\").Limit(5).Offset(0).Get()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tquery.PrintQuery()\n\tfor k, v := range result {\n\t\tfor field, value := range v {\n\t\t\tlog.Println(fmt.Sprintf(\"key = %v =\u003e field = %v, value = %v\", k, field, value))\n\t\t}\n\t}\n}\n```\n\n### WhereIn and WhereNotIn clauses\n\n```go\nresult, err := db.Table(\"or_user\").WhereIn(\"id\", []int64{1, 2, 3}).OrWhereIn(\"name\", []string{\"Aris\", \"Jake\"}).Get()\n```\n\n### WhereNull and WhereNotNull clauses\n\n```go\nresult, err := db.Table(\"or_user\").WhereNull(\"user_id\").OrWhereNotNull(\"username\").Get()\n```\n\n### WhereExists and WhereNotExists clauses\n\nThe whereExists method empowers you to craft SQL clauses for evaluating existence. When using the whereExists method, you can provide a \\*DB argument, which will be assigned a query builder instance. This instance enables you to specify the query that should be enclosed within the \"exists\" clause:\n\n```go\nresult, er := db.Table(\"or_user\").Select(\"username\").WhereExists(\n    db.Table(\"or_user\").Select(\"username\").Where(\"user_id\", \"\u003e=\", int64(12345)),\n).First()\n```\n\n### WhereBetween and WhereNotBetween clauses\n\n```go\nresult, err := db.Table(\"or_user\").Select(\"username\").WhereBetween(\"user_id\", 1111, 4444).Get()\n```\n\n```go\nresult, err := db.Table(\"or_user\").Select(\"username\").WhereNotBetween(\"user_id\", 3333, 5555).Get()\n```\n\n### Left / Right / Inner / Left Outer Joins\n\n```go\nquery := db.\n\t\tTable(\"or_user\").\n\t\tSelect(\"or_user.user_id, or_user.user_name, or_user.phone , or_user.modifydate, or_role.*\").\n\t\tLeftJoin(\"or_user_role\", \"or_user.user_id\", \"=\", \"or_user_role.user_id\").\n\t\tLeftJoin(\"or_role\", \"or_role.role_id\", \"=\", \"or_user_role.role_id\")\n```\n\n### Insert\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest04()\n}\n\nfunc test04() {\n\terr := db.Table(\"table1\").Insert(map[string]interface{}{\"foo\": \"foo foo foo\", \"bar\": \"bar bar bar\", \"baz\": int64(123)})\n\n\t// insert returning id\n\tid, err := db.Table(\"table1\").InsertGetId(map[string]interface{}{\"foo\": \"foo foo foo\", \"bar\": \"bar bar bar\", \"baz\": int64(123)})\n\n\t// batch insert\n\terr = db.Table(\"table1\").InsertBatch([]map[string]interface{}{\n\t\t0: {\"foo\": \"foo foo foo\", \"bar\": \"bar bar bar\", \"baz\": 123},\n\t\t1: {\"foo\": \"foo foo foo foo\", \"bar\": \"bar bar bar bar\", \"baz\": 1234},\n\t\t2: {\"foo\": \"foo foo foo foo foo\", \"bar\": \"bar bar bar bar bar\", \"baz\": 12345},\n\t})\n}\n```\n\n### Update\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest05()\n}\n\nfunc test05() {\n\trows, err := db.Table(\"or_user\").Where(\"user_id\", \"\u003e\", 3).Update(map[string]interface{}{\"username\": \"paul\"})\n}\n```\n\n### Drop, Truncate and Rename\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest06()\n}\n\nfunc test06() {\n\tdb.Drop(\"table_name\")\n\tdb.DropIfExists(\"table_name\")\n\tdb.Truncate(\"table_name\")\n\tdb.Rename(\"table_name1\", \"table_name2\")\n}\n```\n\n### Increment and Decrement\n\nThe query builder offers convenient functions for increasing or decreasing the value of a specified column. This feature serves as a shortcut, presenting a more expressive and concise interface than manually crafting the update statement. Both of these functions require two arguments: the target column and a second parameter to determine the amount by which the column should be incremented or decremented.\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest07()\n}\n\nfunc test07() {\n\tdb.Table(\"or_user\").Increase(\"hit\", 3)\n\tdb.Table(\"or_user\").Decrease(\"hit\", 1)\n}\n```\n\n### Union and Union All\n\nThe query builder also offers a streamlined method to combine two queries using a \"union\" operation. For instance, you can initiate an initial query and employ the union method to unite it with a second query:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/sivaosorg/qb/qb\"\n)\n\nvar db = qb.NewQbDb(qb.NewQbConn(\"postgres\", \"host=127.0.0.1 port=5432 user=db_username dbname=db_name password='password' sslmode=disable\"))\n\nfunc main() {\n\ttest08()\n}\n\nfunc test08() {\n\tunion := db.Table(\"or_user\").Select(\"user_id\", \"user_name\").Union()\n\t// or if UNION ALL is of need\n\t// union := db.Table(\"or_user\").Select(\"user_id\", \"user_name\").UnionAll()\n\tres, err := union.Table(\"or_user_bk\").Select(\"user_id\", \"user_name\").Get()\n}\n```\n\n### Transaction Mode\n\nIn transaction mode, you have the flexibility to execute arbitrary queries alongside your code, allowing for error detection and automatic rollback in case of issues, or successful commit when everything proceeds smoothly:\n\n```go\nerr := db.InTransaction(func() (interface{}, error) {\n    return db.Table(\"or_user\").Select(\"user_name\", \"user_id\", \"phone\").Get()\n})\n```\n\n### Aggregates\n\nFurthermore, the query builder offers a range of aggregate functions, including Count, Max, Min, Avg, and Sum. You can invoke any of these functions once you've constructed your query:\n\n```go\ncnt, err := db.Table(UsersTable).WHere(\"user_id\", \"\u003e=\", 11111).Count()\n\navg, err := db.Table(UsersTable).Avg(\"user_id\")\n\nmx, err := db.Table(UsersTable).Max(\"user_id\")\n\nmn, err := db.Table(UsersTable).Min(\"user_id\")\n\nsum, err := db.Table(UsersTable).Sum(\"user_id\")\n```\n\n### Create Table\n\nFor generating a new database table, employ the CreateTable method. The Schema method necessitates two arguments. The initial argument denotes the table's name, while the second argument is an anonymous function or closure that receives a Table struct, enabling you to define the characteristics of the new table:\n\n```go\nresult, err := db.Schema(\"public\", func(table *Table) error {\n    table.Increments(\"id\")\n    table.String(\"title\", 128).Default(\"The quick brown fox jumped over the lazy dog\").Unique(\"idx_ttl\")\n    table.SmallInt(\"cnt\").Default(1)\n    table.Integer(\"points\").NotNull()\n    table.BigInt(\"likes\").Index(\"idx_likes\")\n    table.Text(\"comment\").Comment(\"user comment\").Collation(\"de_DE\")\n    table.DblPrecision(\"likes_to_points\").Default(0.0)\n    table.Char(\"tag\", 10)\n    table.DateTime(\"created_at\", true)\n    table.DateTimeTz(\"updated_at\", true)\n    table.Decimal(\"tax\", 2, 2)\n    table.TsVector(\"body\")\n    table.TsQuery(\"body_query\")\n    table.Jsonb(\"settings\")\n    table.Point(\"pt\")\n    table.Polygon(\"poly\")\n    table.TableComment(\"big table for big data\")\n\treturn nil\n})\n\n// to make a foreign key constraint from another table\n_, err = db.Schema(\"tbl_ref\", func(table *Table) error {\n    table.Increments(\"id\")\n    table.Integer(\"big_tbl_id\").ForeignKey(\"fk_idx_big_tbl_id\", \"big_tbl\", \"id\").Concurrently().IfNotExists()\n    table.Char(\"tag\", 10).Index(\"idx_tag\").Include(\"likes\", \"created_at\")  // to add index on existing column just repeat stmt + index e.g.:\n    table.Rename(\"settings\", \"options\")\n    return nil\n})\n```\n\n### Add / Modify / Drop columns\n\nThe Table structure provided in the second argument of Schema can also be utilized to update existing tables, much like how it's created initially. The Change method enables you to alter existing column types or modify the attributes of columns within the table.\n\n```go\nresult, err := db.Schema(\"or_user\", func(table *Table) error {\n    table.String(\"user_id\", 128).Change()\n    return nil\n})\n```\n\n```go\nresult, err := db.Schema(\"or_user\", func(table *Table) error {\n    table.DropColumn(\"expired\").IfExists()\n    // To drop an index on the column\n    table.DropIndex(\"idx_user_id\")\n    return nil\n})\n```\n\n### Chunk\n\nWhen dealing with a substantial number of database records, it's advisable to leverage the chunk method. This method retrieves a small portion of the results in each iteration and passes each chunk to a closure for processing.\n\n```go\nerr = db.Table(\"or_user\").Select(\"username\").Where(\"user_id\", \"=\", id).Chunk(300, func(users []map[string]interface{}) bool {\n    for _, m := range users {\n        if val, ok := m[\"user_id\"];ok {\n            calc += diffFormula(val.(int64))\n        }\n        // or you can return false here to stop running chunks\n    }\n    return true\n})\n```\n\n## Ref\n\n- [PostgreSQL](https://popsql.com/learn-sql/postgresql)\n- [Quick tricks in PostgreSQL](https://www.freecodecamp.org/news/postgresql-tricks/)\n\n## Contribution\n\nContributions, bug reports, and feature requests are welcome! Please feel free to open issues and submit pull requests.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsivaosorg%2Fqb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsivaosorg%2Fqb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsivaosorg%2Fqb/lists"}