{"id":29584299,"url":"https://github.com/devscast/queryzen-ts","last_synced_at":"2025-07-20T00:30:45.361Z","repository":{"id":304345669,"uuid":"1018491971","full_name":"devscast/queryzen-ts","owner":"devscast","description":"Typescript SQL Query Builder inspired by Doctrine DBAL","archived":false,"fork":false,"pushed_at":"2025-07-12T12:50:57.000Z","size":106,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-12T14:51:34.991Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","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/devscast.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,"zenodo":null}},"created_at":"2025-07-12T11:28:24.000Z","updated_at":"2025-07-12T12:57:55.000Z","dependencies_parsed_at":"2025-07-12T15:03:26.333Z","dependency_job_id":null,"html_url":"https://github.com/devscast/queryzen-ts","commit_stats":null,"previous_names":["devscast/queryzen-ts"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/devscast/queryzen-ts","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devscast%2Fqueryzen-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devscast%2Fqueryzen-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devscast%2Fqueryzen-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devscast%2Fqueryzen-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/devscast","download_url":"https://codeload.github.com/devscast/queryzen-ts/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devscast%2Fqueryzen-ts/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266048473,"owners_count":23868738,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2025-07-20T00:30:41.331Z","updated_at":"2025-07-20T00:30:45.347Z","avatar_url":"https://github.com/devscast.png","language":"TypeScript","readme":"# QueryZen : TypeScript SQL Query Builder\n\n![npm](https://img.shields.io/npm/v/@devscast/queryzen?style=flat-square)\n![npm](https://img.shields.io/npm/dt/@devscast/queryzen?style=flat-square)\n[![Lint](https://github.com/devscast/queryzen-ts/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/devscast/queryzen-ts/actions/workflows/lint.yml)\n[![Tests](https://github.com/devscast/queryzen-ts/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/devscast/queryzen-ts/actions/workflows/test.yml)\n![GitHub](https://img.shields.io/github/license/devscast/queryzen-ts?style=flat-square)\n\n---\n\n## Overview\nWhile several SQL query builders (including ORM-based ones) already exist in the TypeScript ecosystem, many of them require a live database connection and a data retrieval layer to function. This approach is often ideal for greenfield applications but can become a constraint when integrating into legacy systems or during incremental migrations.\n\nThis library is designed with a single responsibility: to generate MySQL queries as plain SQL strings in a predictable, testable, and fully programmatic manner—without requiring a database connection or execution context. Query generation is its only concern; data retrieval, execution, and schema validation are left to the user.\n\n## Motivation\nThe goal is to simplify and encourage safe query reuse—especially in contexts where introducing a full ORM or runtime dependency is overkill or impractical.\n\nProjects like [sql-bricks](https://www.npmjs.com/package/sql-bricks) and [mysql-bricks](https://www.npmjs.com/package/mysql-bricks) previously served this purpose well, but they are now unmaintained. This library aims to serve as a modern, actively supported alternative, while following the same core principle: build composable SQL statements as strings.\n\n\u003e ⚠️ Note: This library does not provide schema-aware features or type safety tied to your database structure. It focuses solely on SQL string generation.\n\n## Use Case\nThis tool is particularly useful for:\n\n1. Migrating legacy full-text SQL queries to a more robust and maintainable structure.\n2. Writing testable query builders decoupled from database runtime.\n3. Generating reusable query fragments across a large codebase.\n\n## Installation\n\nThis library is a partial port of the Doctrine DBAL QueryBuilder and offers a nearly identical API. \nThe core query builder is fully implemented, and for documentation and advanced usage patterns, you can refer to the official Doctrine DBAL guide: https://www.doctrine-project.org/projects/doctrine-dbal/en/4.2/reference/query-builder.html.\n\n```bash\nnpm install @devscast/queryzen\n```\n\n### Example Usage\n\n#### 1. Building a dynamic user search query with optional filters\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\ninterface UserFilters {\n    username?: string;\n    minAge?: number;\n    isActive?: boolean;\n}\n\nconst searchUserQuery = (filters: UserFilters): QueryBuilder =\u003e {\n    const qb = new QueryBuilder()\n        .select('u.id', 'u.username', 'u.email', 'u.created_at')\n        .from('users', 'u');\n\n    if (filters.username) {\n        qb.andWhere('u.username LIKE :username');\n        qb.setParameter('username', `%${filters.username}%`);\n    }\n\n    if (filters.minAge !== undefined) {\n        qb.andWhere('u.age \u003e= :minAge');\n        qb.setParameter('minAge', filters.minAge);\n    }\n\n    if (filters.isActive !== undefined) {\n        qb.andWhere('u.is_active = :isActive');\n        qb.setParameter('isActive', filters.isActive);\n    }\n\n    qb.orderBy('u.created_at', 'DESC');\n\n    return qb\n}\n\nconst query = searchUserQuery({ username: 'john', isActive: true });\n\n// query.toString() =\u003e \"\n    // SELECT u.id, u.username, u.email, u.created_at \n    // FROM `users` AS u \n    // WHERE u.username LIKE :username AND u.is_active = :isActive \n    // ORDER BY u.created_at DESC\"\n// { ...query.getParameters() } =\u003e { username: '%john%', isActive: true }\n```\n\n#### 2. Fetching posts with authors and optional category filtering\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\ninterface PostFilters {\n  categoryId?: number;\n  isPublished?: boolean;\n  authorName?: string;\n}\n\nconst getPostListQuery = (filters: PostFilters): QueryBuilder =\u003e {\n  const qb = new QueryBuilder()\n    .select(\n      'p.id',\n      'p.title',\n      'p.slug',\n      'p.created_at',\n      'a.id AS author_id',\n      'a.name AS author_name',\n      'c.name AS category_name'\n    )\n    .from('posts', 'p')\n    .innerJoin('p', 'author', 'a', 'p.author_id = a.id')\n    .leftJoin('p', 'category', 'c', 'p.category_id = c.id');\n\n  if (filters.isPublished !== undefined) {\n    qb.andWhere('p.is_published = :isPublished');\n    qb.setParameter('isPublished', filters.isPublished);\n  }\n\n  if (filters.categoryId !== undefined) {\n    qb.andWhere('p.category_id = :categoryId');\n    qb.setParameter('categoryId', filters.categoryId);\n  }\n\n  if (filters.authorName) {\n    qb.andWhere('a.name LIKE :authorName');\n    qb.setParameter('authorName', `%${filters.authorName}%`);\n  }\n\n  qb.orderBy('p.created_at', 'DESC');\n\n  return qb;\n}\n\nconst query = getPostListQuery({ isPublished: true });\n```\n\n#### 3. Using CTEs to fetch active users with their latest login\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\n// Step 1: Define the CTE for latest logins per user\nconst lastLoginQuery = new QueryBuilder()\n    .select('l.user_id', 'MAX(l.logged_in_at) AS last_login_at')\n    .from('logins', 'l')\n    .groupBy('l.user_id');\n\n// Step 2: Main query using the CTE\nconst qb = new QueryBuilder()\n    .with('last_login', lastLoginQuery)\n    .select('u.id', 'u.name', 'u.email', 'll.last_login_at')\n    .from('users', 'u')\n    .innerJoin('u', 'last_login', 'll', 'll.user_id = u.id')\n    .where('u.is_active = true')\n    .orderBy('ll.last_login_at', 'DESC');\n```\n\n#### 4. Deleting users by status\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\nconst qb = new QueryBuilder()\n    .delete('users').where('name = :name')\n    .setParameter('name', 'John Doe');\n\n// qb.toString() =\u003e \"DELETE FROM `users` WHERE name = :name\"\n// { ...qb.getParameters() } =\u003e { name: 'John Doe' }\n```\n\n#### 5. Inserting a new user\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\nconst data = { name: 'John Doe', email: 'john.doe@test.com' }\nconst qb = new QueryBuilder().upsert('users', data, 'insert', 'positional');\n\n// qb.toString() =\u003e \"INSERT INTO `users` (name, email) VALUES (?, ?)\"\n// qb.getParameters() =\u003e ['John Doe', 'john.doe@test.com' ]\n```\n\n#### 6. Updating a user\n```typescript\nimport { QueryBuilder } from '@devscast/queryzen';\n\nconst data = { name: 'Jane Doe', email: 'jane.doe@test.com' }\nconst qb = new QueryBuilder()\n    .upsert('users', data, 'update', 'named')\n    .where('id = :id')\n    .setParameter('id', 123);\n\n// qb.toString() =\u003e \"UPDATE `users` SET name = :name, email = :email WHERE id = :id\"\n// { ...qb.getParameters() } =\u003e { name: 'Jane Doe', email: 'jane.doe@test.com' }\n```\n\n### Security Notice: SQL Injection\n\nWe **highly recommend using prepared statements** with parameter binding to prevent SQL injection vulnerabilities. This library supports both named and positional parameters via `.setParameter()` and `.setParameters()`, and you can retrieve all parameters using `.getParameters()` to pass them safely to your database driver.\n\n\u003e ⚠️ Important: While the query builder performs basic SQL identifier escaping by default (e.g., table and column names), this is not sufficient to prevent SQL injection if you interpolate raw values into your query strings. It is your responsibility to ensure that values are always bound through parameters.\n\nAlways validate and sanitize inputs appropriately, especially when integrating with raw database drivers or legacy systems.\n\n## Contributors\n\n\u003ca href=\"https://github.com/devscast/queryzen-tz/graphs/contributors\" title=\"show all contributors\"\u003e\n  \u003cimg src=\"https://contrib.rocks/image?repo=devscast/queryzen-ts\" alt=\"contributors\"/\u003e\n\u003c/a\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevscast%2Fqueryzen-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevscast%2Fqueryzen-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevscast%2Fqueryzen-ts/lists"}