How to check if an entry already exist?

I found this query to check if an entry in the table already exists:
await db.execute(
sql`select exists(select 1 from ${posts} where ${posts.slug} = ${slug})`,
)
await db.execute(
sql`select exists(select 1 from ${posts} where ${posts.slug} = ${slug})`,
)
Which returns the response: Result(1) [ { exists: false } ] but how do I use it in a typescript if statement to run conditional code?
5 Replies
tzezar
tzezar8mo ago
Probably not the best solution, but I do
let [s] = await tx
.select()
.from(settlement)
.where(eq(settlement.id, settlementId))
if (!s) {
throw new Error("settlement not found")
let [s] = await tx
.select()
.from(settlement)
.where(eq(settlement.id, settlementId))
if (!s) {
throw new Error("settlement not found")
Mykhailo
Mykhailo8mo ago
Hello, @textYash! Your solution is good to check if an entry exists in the table. Could you please clarify what you want to achieve with if statement? this works too!
textYash
textYashOP8mo ago
I'm not sure how to use the result returned by that query inside an if statement to take an action based on it
Which returns the response: Result(1) [ { exists: false } ]
I'm using typescript so how can I use eq or === on this?
Mykhailo
Mykhailo8mo ago
@textYash you can do smth like this
const [{ exists }] = await db.execute<{ exists: boolean }>(
sql`select exists(select 1 from ${posts} where ${posts.slug} = ${slug})`,
);

if (exists) {
console.log('exists');
} else {
console.log('does not exist');
}
const [{ exists }] = await db.execute<{ exists: boolean }>(
sql`select exists(select 1 from ${posts} where ${posts.slug} = ${slug})`,
);

if (exists) {
console.log('exists');
} else {
console.log('does not exist');
}
textYash
textYashOP8mo ago
Oh twas easy Thanks SOLVED
Want results from more Discord servers?
Add your server