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

Fix inconsistent results from raw SQL #11091

Merged
merged 4 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/honest-shirts-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@astrojs/db": patch
---

Fix inconsistent result type using raw SQL
18 changes: 17 additions & 1 deletion packages/db/src/runtime/db-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,23 @@ export function createRemoteDatabaseClient(appToken: string, remoteDbURL: string
});
}

if (method === 'run') return remoteResult;
if (method === 'run') {
const rawRows = Array.from(remoteResult.rows);
// Implement basic `toJSON()` for Drizzle to serialize properly
(remoteResult as any).rows.toJSON = () => rawRows;
// Using `db.run()` drizzle massages the rows into an object.
// So in order to make dev/prod consistent, we need to do the same here.
// This creates an object and loops over each row replacing it with the object.
for(let i = 0; i < remoteResult.rows.length; i++) {
let row = remoteResult.rows[i];
let item: Record<string, any> = {};
remoteResult.columns.forEach((col, index) => {
item[col] = row[index];
});
(remoteResult as any).rows[i] = item;
}
return remoteResult;
}

// Drizzle expects each row as an array of its values
const rowValues: unknown[][] = [];
Expand Down
17 changes: 17 additions & 0 deletions packages/db/test/fixtures/static-remote/src/pages/run.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
import { User, db, sql } from 'astro:db';

const results = await db.run(sql`SELECT 1 as value`);
const row = results.rows[0];
---

<html>
<head>
<title>Testing</title>
</head>
<body>
<h1>Testing</h1>

<span id="row">{row.value}</span>
</body>
</html>
7 changes: 7 additions & 0 deletions packages/db/test/static-remote.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,12 @@ describe('astro:db', () => {

expect($('li').length).to.equal(1);
});

it('Returns correct shape from db.run()', async () => {
const html = await fixture.readFile('/run/index.html');
const $ = cheerioLoad(html);

expect($('#row').text()).to.equal('1');
});
});
});
Loading