Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement type predicates for query builders #846

Closed
wants to merge 4 commits into from

Conversation

garymathews
Copy link
Contributor

@garymathews garymathews commented Jan 16, 2024

  • Similar to the existing SelectQueryBuilder.isSelectQueryBuilder property, implemented:
    • InsertQueryBuilder.isInsertQueryBuilder
    • UpdateQueryBuilder.isUpdateQueryBuilder
    • DeleteQueryBuilder.isDeleteQueryBuilder
    • MergeQueryBuilder.isMergeQueryBuilder
  • Implemented type predicate methods for each query builder:
    • isSelectQueryBuilder(qb)
    • isInsertQueryBuilder(qb)
    • isUpdateQueryBuilder(qb)
    • isDeleteQueryBuilder(qb)
    • isMergeQueryBuilder(qb)
  • Added AnyQueryBuilder type

Examples

import { AnyQueryBuilder, isSelectQueryBuilder } from 'kysely'

function explainSelect<DB, TB extends keyof DB, O>(qb: AnyQueryBuilder<DB, TB, O>) {
  if (isSelectQueryBuilder(qb)) {
    // TypeScript determines `qb` as being of type `SelectQueryBuilder` whithin this scope
    return query.explain('json')
  }
  return query
}
import { AnyQueryBuilder, InsertResult, DeleteResult, isInsertQueryBuilder } from 'kysely'

const queries: AnyQueryBuilder<Database, 'person', InsertResult | DeleteResult>[] = [
  db.insertInto('person').values({ first_name: 'Mary', last_name: 'Shelley', gender: 'female' }),
  db.deleteFrom('person').where('first_name', '=', 'Ann'),
  db.insertInto('person').values({ first_name: 'Bram', last_name: 'Stoker', gender: 'male' })
]

// Grab all `InsertQueryBuilder` queries
const insertQueries = queries.filter(isInsertQueryBuilder)
// TypeScript identifies `insertQueries` as being of type `InsertQueryBuilder[]`

Copy link

vercel bot commented Jan 16, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
kysely ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 21, 2024 9:12am

@garymathews
Copy link
Contributor Author

@koskimas is this something you're open to adding?

@igalklebanov
Copy link
Member

igalklebanov commented Mar 26, 2024

Hey 👋

Thank you! 💪

Can you explain the real-world use of this?

@igalklebanov igalklebanov added enhancement New feature or request api Related to library's API labels Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Related to library's API enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants