-
-
Notifications
You must be signed in to change notification settings - Fork 229
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
2 additions
and
51 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ import { dataSource } from "./dataSource.dbtests.js" | |
import { knex, Knex } from "knex" | ||
import { getConnection, knexRaw } from "../db.js" | ||
import { DataSource } from "typeorm" | ||
import { insertUser, updateUser, User } from "../model/User.js" | ||
import { deleteUser, insertUser, updateUser, User } from "../model/User.js" | ||
import { Chart } from "../model/Chart.js" | ||
import { DbPlainUser, UsersTableName } from "@ourworldindata/types" | ||
|
||
|
@@ -137,55 +137,6 @@ test("knex interface", async () => { | |
[UsersTableName] | ||
) | ||
expect(usersFromRawQuery.length).toBe(2) | ||
}) | ||
}) | ||
|
||
test("knex interface raw", async () => { | ||
if (!knexInstance) throw new Error("Knex connection not initialized") | ||
|
||
// Create a transaction and run all tests inside it | ||
await knexInstance.transaction(async (trx) => { | ||
// Fetch all users into memory | ||
const users = await trx | ||
.from<DbPlainUser>(UsersTableName) | ||
.select("isSuperuser", "email") | ||
expect(users.length).toBe(1) | ||
|
||
// Fetch all users in a streaming fashion, iterate over them async to avoid having to load everything into memory | ||
const usersStream = trx | ||
.from<DbPlainUser>(UsersTableName) | ||
.select("isSuperuser", "email") | ||
.stream() | ||
|
||
for await (const user of usersStream) { | ||
expect(user.isSuperuser).toBe(0) | ||
expect(user.email).toBe("[email protected]") | ||
} | ||
|
||
// Use the insert helper method | ||
await insertUser(trx, { | ||
email: "[email protected]", | ||
fullName: "Test User", | ||
}) | ||
|
||
// Use the update helper method | ||
await updateUser(trx, 2, { isSuperuser: 1 }) | ||
|
||
// Check results after update and insert | ||
const afterUpdate = await trx | ||
.from<DbPlainUser>(UsersTableName) | ||
.select("isSuperuser", "email") | ||
.orderBy("id") | ||
expect(afterUpdate.length).toBe(2) | ||
expect(afterUpdate[1].isSuperuser).toBe(1) | ||
|
||
// Use raw queries, using ?? to specify the table name using the shared const value | ||
// The pick type is used to type the result row | ||
const usersFromRawQuery: Pick<DbPlainUser, "email">[] = await knexRaw( | ||
"select email from ??", | ||
trx, | ||
[UsersTableName] | ||
) | ||
expect(usersFromRawQuery.length).toBe(2) | ||
await deleteUser(trx, 2) | ||
}) | ||
}) |