mirror of
https://github.com/oven-sh/bun
synced 2026-02-02 15:08:46 +00:00
### What does this PR do? Fixes the postgres benchmark so that it actually benchmarks query performance on node and deno. Before this PR, the `sql` function was just creating a tagged template function, which involved connecting to the database. So basically bun was doing queries, but node and deno were just connecting to the postgres database over and over. You can see from the first example in the docs that you're supposed to call the default export in order to get back a function to use with template literals: https://www.npmjs.com/package/postgres ### How did you verify your code works? Ran it
46 lines
1.3 KiB
JavaScript
46 lines
1.3 KiB
JavaScript
const isBun = typeof globalThis?.Bun?.sql !== "undefined";
|
|
import postgres from "postgres";
|
|
const sql = isBun ? Bun.sql : postgres();
|
|
|
|
// Create the table if it doesn't exist
|
|
await sql`
|
|
CREATE TABLE IF NOT EXISTS "users_bun_bench" (
|
|
id SERIAL PRIMARY KEY,
|
|
first_name TEXT NOT NULL,
|
|
last_name TEXT NOT NULL,
|
|
email TEXT NOT NULL UNIQUE,
|
|
dob TEXT NOT NULL
|
|
)
|
|
`;
|
|
|
|
// Check if users already exist
|
|
const existingUsers = await sql`SELECT COUNT(*) as count FROM "users_bun_bench"`;
|
|
|
|
if (+(existingUsers?.[0]?.count ?? existingUsers?.count) < 100) {
|
|
// Generate 100 users if none exist
|
|
const users = Array.from({ length: 100 }, (_, i) => ({
|
|
first_name: `FirstName${i}`,
|
|
last_name: `LastName${i}`,
|
|
email: `user${i}@example.com`,
|
|
dob: new Date(1970 + Math.floor(Math.random() * 30), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28))
|
|
.toISOString()
|
|
.split("T")[0],
|
|
}));
|
|
|
|
// Insert all users
|
|
await sql`INSERT INTO users_bun_bench ${sql(users)}`;
|
|
}
|
|
|
|
const type = isBun ? "Bun.sql" : "postgres";
|
|
console.time(type);
|
|
let promises = [];
|
|
for (let i = 0; i < 100_000; i++) {
|
|
promises.push(sql`SELECT * FROM "users_bun_bench" LIMIT 100`);
|
|
if (i % 100 === 0 && promises.length > 1) {
|
|
await Promise.all(promises);
|
|
promises.length = 0;
|
|
}
|
|
}
|
|
await Promise.all(promises);
|
|
console.timeEnd(type);
|