Execution flow
The following page gives a simplified overview of Kysely's execution flow, from query building to querying the database. It is a nice introduction for anyone looking to understand how Kysely works under the hood. Knowing what your dependencies do and don't do is always a good idea!
This breakdown explains the journey from a type-safe method call in your application to receiving results from the database, as depicted in the diagram.
-
Immutable query building
The process starts in your
App. You interact with theQueryBuilderby calling its methods (selectFrom,where, etc.). Each call returns a newQueryBuilderinstance containing an updated, immutableQueryAST(Abstract Syntax Tree), which is the internal representation of your SQL query. -
Initiating execution
When you chain the final
.execute()call, theQueryBuilderbegins a multi-step execution process, commanding theQueryExecutorto perform distinct tasks. -
Query Transformation
First, the
QueryBuilderinstructs theQueryExecutorto process theQueryAST. TheQueryExecutoriterates through all registered plugins, callingtransformQueryon each. This allows plugins to modify the query structure before compilation. The final, transformedQueryASTis returned to theQueryBuilder. -
Query Compilation
Next, the
QueryBuildertells theQueryExecutorto compile the transformed AST. TheQueryExecutordelegates this to theDialect-specificQueryCompiler. The compiler traverses the AST and produces aCompiledQueryobject (containing the final SQL string and parameters). ThisCompiledQueryis then returned to theQueryBuilder. -
Execution & Connection Handling
The
QueryBuildernow asks theQueryExecutorto execute theCompiledQuery.- The
QueryExecutorrequests a connection from Kysely'sDriver. - The
Driver's job is to abstract away vendor-specific details. It communicates with the actual third-partyDatabaseDriver— for example, thepgormysql2npm package — to get a connection from its pool. - A
DatabaseConnectionobject, which wraps the native connection, is returned to theQueryExecutor.
- The
-
Database Query
The
QueryExecutorpasses theCompiledQueryto theDatabaseConnectionobject, which executes it. TheDatabaseConnectionuses the underlyingDatabaseDriverto send the SQL and parameters to the database for execution. TheDatabaseDriversends the raw results back. TheDatabaseConnectionstandardizes these into aQueryResultobject and returns it to theQueryExecutor. Immediately after, the connection is released back to the pool. -
Result Transformation
The
QueryResultis then passed through the plugin system again. TheQueryExecutorcalls thetransformResultmethod on each plugin, allowing for final modifications to the results before they are returned to theApp. -
Returning to the App
The final, transformed
QueryResultis passed up from theQueryExecutorto theQueryBuilder. TheQueryBuilderthen resolves the promise from the initial.execute()call, delivering the final, typed results to yourApp.