Skip to content

Commit 06d827d

Browse files
committed
Use postgres instance directly for raw queries
1 parent a98ce0f commit 06d827d

5 files changed

Lines changed: 12 additions & 19 deletions

File tree

apps/api/src/helpers/context.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ type User = {
1313
}
1414

1515
export type Context = {
16-
postgres: Postgres.Sql
16+
sql: Postgres.Sql
1717
db: PostgresJsDatabase<typeof schema>
1818
log: Logger
1919
config: typeof config
@@ -42,11 +42,6 @@ export async function createRequestContext(context: RequestContext): Promise<Req
4242
return context
4343
}
4444

45-
export function createContext({
46-
postgres,
47-
db,
48-
log,
49-
config
50-
}: Pick<Context, 'postgres' | 'db' | 'log' | 'config'>): Context {
51-
return { log, db, postgres, config }
45+
export function createContext({ sql, db, log, config }: Pick<Context, 'sql' | 'db' | 'log' | 'config'>): Context {
46+
return { log, db, sql, config }
5247
}

apps/api/src/helpers/shutdown.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ async function initiateShutdown(context: Context, event, err: any, close: () =>
7676
await close()
7777

7878
log.info('Closing connection pool')
79-
await context.postgres.end()
79+
await context.sql.end()
8080
} catch (e) {
8181
log.error(e, 'Failed to close server')
8282
process.exit(1)

apps/api/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { shutdown } from './helpers/shutdown.ts'
1111
import { sendTelegram } from './modules/errors/helpers/sendTelegram.ts'
1212

1313
const log = pino({ level: 'debug', timestamp: pino.stdTimeFunctions.isoTime })
14-
const context = createContext({ db, postgres, log, config })
14+
const context = createContext({ db, sql: postgres, log, config })
1515
const app = initApp({ context })
1616
initRoutes({ app })
1717
initGraphql({ app })

apps/api/src/modules/readings/loaders.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { desc, sql } from 'drizzle-orm'
1+
import { desc } from 'drizzle-orm'
22
import { inArray } from 'drizzle-orm/sql/expressions/conditions'
33
import { type Context } from '../../helpers/context.ts'
44
import { readings } from '../../helpers/schema.ts'
@@ -17,17 +17,17 @@ export default {
1717
},
1818
lastWateredTime: async (queries, context: Context) => {
1919
const deviceIds = queries.map((query) => query.obj.id)
20-
const result = await context.db.execute<{ time: string; device_id: string }>(sql`
20+
const result = await context.sql<{ time: string; device_id: string }[]>`
2121
SELECT DISTINCT ON (device_id) *
2222
FROM (SELECT device_id,
2323
time::timestamptz,
2424
moisture - lead(moisture) OVER (PARTITION BY device_id ORDER BY time DESC) AS moisture_increase
2525
FROM readings
26-
WHERE device_id = ANY (ARRAY [${sql(deviceIds.join(','))}]::bigint[])
26+
WHERE device_id IN ${context.sql(deviceIds)}
2727
AND time > now() - '90 days'::interval) AS readings
2828
WHERE moisture_increase > 10
2929
ORDER BY device_id, time DESC;
30-
`)
30+
`
3131

3232
return queries.map((query) => {
3333
const time = result.find((entry) => entry.device_id === `${query.obj.id}`)?.time
@@ -36,8 +36,7 @@ export default {
3636
},
3737
readings: async (queries, context: Context) => {
3838
const deviceIds = queries.map((query) => query.obj.id)
39-
const result = await context.db.execute(
40-
sql`
39+
const result = await context.sql`
4140
SELECT device_id, day AS time, moisture, temperature, light, battery_voltage AS "batteryVoltage"
4241
FROM (SELECT device_id,
4342
time_bucket_gapfill('1 day'::interval, time) AS day,
@@ -46,14 +45,13 @@ export default {
4645
locf(avg(light)) AS light,
4746
locf(avg(battery_voltage)) AS battery_voltage
4847
FROM readings
49-
WHERE device_id = ANY (ARRAY [${sql(deviceIds.join(','))}]::bigint[])
48+
WHERE device_id IN ${context.sql(deviceIds)}
5049
AND time > now() - INTERVAL '90 days'
5150
AND time < now()
5251
GROUP BY day, device_id
5352
ORDER BY day ASC) AS readings
5453
WHERE moisture IS NOT NULL; -- Exclude entries with non-null readings that can occur when period is before first readings.
5554
`
56-
)
5755

5856
return queries.map((query) => result.filter((entry) => entry.device_id === `${query.obj.id}`))
5957
}

apps/api/src/test-helpers/setupGraphql.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export function setupGraphql() {
2020

2121
beforeEach(async () => {
2222
context.db = dbResult.db
23-
context.postgres = dbResult.sql
23+
context.sql = dbResult.sql
2424
result.context = createContext({
2525
...result.context,
2626
db: dbResult.db,

0 commit comments

Comments
 (0)