Home

Connecting directly to Postgres

Supabase Edge Functions allow you to go beyond HTTP and can connect to your Postgres Database directly!

index.ts

_43
import * as postgres from 'https://deno.land/x/postgres@v0.14.2/mod.ts'
_43
import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'
_43
_43
// Get the connection string from the environment variable "SUPABASE_DB_URL"
_43
const databaseUrl = Deno.env.get('SUPABASE_DB_URL')!
_43
_43
// Create a database pool with three connections that are lazily established
_43
const pool = new postgres.Pool(databaseUrl, 3, true)
_43
_43
serve(async (_req) => {
_43
try {
_43
// Grab a connection from the pool
_43
const connection = await pool.connect()
_43
_43
try {
_43
// Run a query
_43
const result = await connection.queryObject`SELECT * FROM animals`
_43
const animals = result.rows // [{ id: 1, name: "Lion" }, ...]
_43
console.log(animals)
_43
_43
// Encode the result as pretty printed JSON
_43
const body = JSON.stringify(
_43
animals,
_43
(key, value) => (typeof value === 'bigint' ? value.toString() : value),
_43
2
_43
)
_43
_43
// Return the response with the correct content type header
_43
return new Response(body, {
_43
status: 200,
_43
headers: {
_43
'Content-Type': 'application/json; charset=utf-8',
_43
},
_43
})
_43
} finally {
_43
// Release the connection back into the pool
_43
connection.release()
_43
}
_43
} catch (err) {
_43
console.error(err)
_43
return new Response(String(err?.message ?? err), { status: 500 })
_43
}
_43
})