Skip to content
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"mysql2": "^3.11.4",
"node-sql-parser": "^4.18.0",
"pg": "^8.13.1",
"postgres": "^3.4.5",
"svix": "^1.59.2",
"tailwind-merge": "^2.6.0",
"vite": "^5.4.11"
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ export class StarbaseDB {
})
})

this.app.get('/status/database', async (c) => {
return createResponse(
{
dialects: {
external: this.dataSource.external?.dialect,
hyperdrive: 'postgresql',
},
},
undefined,
200
)
})

if (this.getFeature('rest')) {
this.app.all('/rest/*', async (c) => {
return this.liteREST.handleRequest(c.req.raw)
Expand Down
32 changes: 25 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { QueryLogPlugin } from '../plugins/query-log'
import { StatsPlugin } from '../plugins/stats'
import { CronPlugin } from '../plugins/cron'
import { InterfacePlugin } from '../plugins/interface'
import { ClerkPlugin } from '../plugins/clerk'

export { StarbaseDBDurableObject } from './do'

Expand Down Expand Up @@ -55,6 +54,8 @@ export interface Env {
AUTH_ALGORITHM?: string
AUTH_JWKS_ENDPOINT?: string

HYPERDRIVE: Hyperdrive

// ## DO NOT REMOVE: TEMPLATE INTERFACE ##
}

Expand Down Expand Up @@ -111,20 +112,30 @@ export default {
source: source
? source.toLowerCase().trim() === 'external'
? 'external'
: 'internal'
: source.toLowerCase().trim() === 'hyperdrive'
? 'hyperdrive'
: 'internal'
: 'internal',
cache: request.headers.get('X-Starbase-Cache') === 'true',
context: {
...context,
},
executionContext: ctx,
}

if (
env.EXTERNAL_DB_TYPE === 'postgresql' ||
env.EXTERNAL_DB_TYPE === 'mysql'
) {
if (env.EXTERNAL_DB_TYPE === 'postgresql') {
dataSource.external = {
dialect: env.EXTERNAL_DB_TYPE,
dialect: 'postgresql',
host: env.EXTERNAL_DB_HOST!,
port: env.EXTERNAL_DB_PORT!,
user: env.EXTERNAL_DB_USER!,
password: env.EXTERNAL_DB_PASS!,
database: env.EXTERNAL_DB_DATABASE!,
defaultSchema: env.EXTERNAL_DB_DEFAULT_SCHEMA,
}
} else if (env.EXTERNAL_DB_TYPE === 'mysql') {
dataSource.external = {
dialect: 'mysql',
host: env.EXTERNAL_DB_HOST!,
port: env.EXTERNAL_DB_PORT!,
user: env.EXTERNAL_DB_USER!,
Expand Down Expand Up @@ -166,6 +177,13 @@ export default {
}
}

if (env.HYPERDRIVE.connectionString) {
dataSource.external = {
dialect: 'postgresql',
connectionString: env.HYPERDRIVE.connectionString,
}
}

const config: StarbaseDBConfiguration = {
outerbaseApiKey: env.OUTERBASE_API_KEY,
role,
Expand Down
10 changes: 8 additions & 2 deletions src/literest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,14 @@ export class LiteREST {
): Promise<string[]> {
let query = `PRAGMA table_info(${tableName});`

if (this.dataSource.source === 'external') {
if (this.dataSource.external?.dialect === 'postgresql') {
if (
this.dataSource.source === 'external' ||
this.dataSource.source === 'hyperdrive'
) {
if (
this.dataSource.external?.dialect === 'postgresql' ||
this.dataSource.source === 'hyperdrive'
) {
query = `
SELECT kcu.column_name AS name
FROM information_schema.table_constraints tc
Expand Down
34 changes: 33 additions & 1 deletion src/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { Client as PgClient } from 'pg'
import { createConnection as createMySqlConnection } from 'mysql2'
import { createClient as createTursoConnection } from '@libsql/client/web'
import postgres from 'postgres'

// Import how we interact with the databases through the Outerbase SDK
import {
Expand All @@ -23,7 +24,6 @@ import { afterQueryCache, beforeQueryCache } from './cache'
import { isQueryAllowed } from './allowlist'
import { applyRLS } from './rls'
import type { SqlConnection } from '@outerbase/sdk/dist/connections/sql-base'
import { StarbasePlugin } from './plugin'

export type OperationQueueItem = {
queries: { sql: string; params?: any[] }[]
Expand Down Expand Up @@ -257,6 +257,38 @@ export async function executeQuery(opts: {
console.error('Returning empty array.')
return []
}
} else if (dataSource.source === 'hyperdrive') {
if (
!dataSource.external ||
!('connectionString' in dataSource.external)
) {
throw new Error('Hyperdrive connection string not found')
}

// Construct a Postgres pool for Hyperdrive connection.
// Currently Hyperdrive only supports Postgres and in the near future should also
// gain support for MySQL which we will then need to make driver updates per the
// docs as they are released.
const sql = postgres(dataSource.external.connectionString, {
max: 5,
fetch_types: false,
})

try {
result = await sql.unsafe(updatedSQL, updatedParams as any[])

if (opts.dataSource?.executionContext) {
// Optimistically we hope a ExecutionContext is available to us
// to properly end our SQL function.
opts.dataSource?.executionContext?.waitUntil(sql.end())
} else {
// As a fallback we'll just end it.
await sql.end()
}
} catch (e) {
console.error('Hyperdrive query error:', e)
throw e
}
} else {
result = await executeExternalQuery({
sql: updatedSQL,
Expand Down
11 changes: 9 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { StarbaseDBDurableObject } from './do'
import { StarbasePlugin, StarbasePluginRegistry } from './plugin'
import { StarbasePluginRegistry } from './plugin'

export type QueryResult = Record<string, SqlStorageValue>

Expand All @@ -12,6 +12,11 @@ export type RemoteSource = {
defaultSchema?: string
}

export type HyperdriveSource = {
dialect: 'postgresql'
connectionString: string
} & Pick<RemoteSource, 'defaultSchema'>

export type PostgresSource = {
dialect: 'postgresql'
} & RemoteSource
Expand Down Expand Up @@ -48,15 +53,17 @@ export type ExternalDatabaseSource =
| CloudflareD1Source
| StarbaseDBSource
| TursoDBSource
| HyperdriveSource

export type DataSource = {
rpc: Awaited<ReturnType<DurableObjectStub<StarbaseDBDurableObject>['init']>>
source: 'internal' | 'external'
source: 'internal' | 'external' | 'hyperdrive'
external?: ExternalDatabaseSource
context?: Record<string, unknown>
cache?: boolean
cacheTTL?: number
registry?: StarbasePluginRegistry
executionContext?: ExecutionContext
}

export enum RegionLocationHint {
Expand Down
4 changes: 4 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,7 @@ ENABLE_RLS = 0

AUTH_ALGORITHM = "RS256"
AUTH_JWKS_ENDPOINT = ""

# [[hyperdrive]]
# binding = "HYPERDRIVE"
# id = ""
Loading