Executing raw Sql query

Is it possible to execute sql in postgres database: string query = "select * from users"; await db.execute(query)
4 Replies
wkd9241
wkd9241•8mo ago
import {sql} from 'drizzle-orm'

// One way
const query = sql.raw('SELECT * from users')

// You can also use string interpolation
const table = "users"
const query = sql.raw(`SELECT * from ${table}`)

// Execute the query
await db.execute(query)
import {sql} from 'drizzle-orm'

// One way
const query = sql.raw('SELECT * from users')

// You can also use string interpolation
const table = "users"
const query = sql.raw(`SELECT * from ${table}`)

// Execute the query
await db.execute(query)
ball 3
ball 3•8mo ago
thx, i have written this code in order to execute a sql query:
import "server-only";

import { db } from "@/db";
import { sql } from "drizzle-orm";

export async function runQuery(query: string) {
const res = await db.execute(sql.raw(query));
return res;
}
import "server-only";

import { db } from "@/db";
import { sql } from "drizzle-orm";

export async function runQuery(query: string) {
const res = await db.execute(sql.raw(query));
return res;
}
and when i call the function for this query:
const res = await runQuery(
"select * from user"
);
const res = await runQuery(
"select * from user"
);
i get [{"user":"default"}] which i also get in the drizzle studio although i do have rows in the user table:
export const users = pgTable("user", {
id: text("id")
.primaryKey()
.$defaultFn(() => uuidv4()),
name: text("name").notNull(),
password: text("password"),
email: text("email").unique().notNull(),
emailVerified: timestamp("emailVerified", { mode: "date" }),
image: text("image")
.default("https://cdn-icons-png.flaticon.com/512/1531/1531344.png")
.notNull(),
role: userRole("role").default("USER").notNull(),
isTwoFactorEnabled: boolean("isTwoFactorEnabled").default(false).notNull(),
});
export const users = pgTable("user", {
id: text("id")
.primaryKey()
.$defaultFn(() => uuidv4()),
name: text("name").notNull(),
password: text("password"),
email: text("email").unique().notNull(),
emailVerified: timestamp("emailVerified", { mode: "date" }),
image: text("image")
.default("https://cdn-icons-png.flaticon.com/512/1531/1531344.png")
.notNull(),
role: userRole("role").default("USER").notNull(),
isTwoFactorEnabled: boolean("isTwoFactorEnabled").default(false).notNull(),
});
is there a way to fix that (note, it does that only for the user table not any other table)
wkd9241
wkd9241•8mo ago
Hmm, I can't help you further. I've started using Drizzle a couple days ago and just happened to have made a raw sql query, so I had the answer to your question. Regarding your other issue, unfortunately I can't spot the error 🫤
ball 3
ball 3•8mo ago
ok thx anyways
Want results from more Discord servers?
Add your server