MCPcopy Create free account
hub / github.com/porsager/postgres / scope

Function scope

deno/src/index.js:252–298  ·  view source on GitHub ↗
(c, fn, name)

Source from the content-addressed store, hash-verified

250 }
251
252 async function scope(c, fn, name) {
253 const sql = Sql(handler)
254 sql.savepoint = savepoint
255 sql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)
256 let uncaughtError
257 , result
258
259 name && await sql`savepoint ${ sql(name) }`
260 try {
261 result = await new Promise((resolve, reject) => {
262 const x = fn(sql)
263 Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject)
264 })
265
266 if (uncaughtError)
267 throw uncaughtError
268 } catch (e) {
269 await (name
270 ? sql`rollback to ${ sql(name) }`
271 : sql`rollback`
272 )
273 throw e instanceof PostgresError && e.code === '25P02' && uncaughtError || e
274 }
275
276 if (!name) {
277 prepare
278 ? await sql`prepare transaction '${ sql.unsafe(prepare) }'`
279 : await sql`commit`
280 }
281
282 return result
283
284 function savepoint(name, fn) {
285 if (name && Array.isArray(name.raw))
286 return savepoint(sql => sql.apply(sql, arguments))
287
288 arguments.length === 1 && (fn = name, name = null)
289 return scope(c, fn, 's' + savepoints++ + (name ? '_' + name : ''))
290 }
291
292 function handler(q) {
293 q.catch(e => uncaughtError || (uncaughtError = e))
294 c.queue === full
295 ? queries.push(q)
296 : c.execute(q) || move(c, full)
297 }
298 }
299
300 function onexecute(c) {
301 connection = c

Callers 2

beginFunction · 0.70
savepointFunction · 0.70

Calls 4

SqlFunction · 0.70
sqlFunction · 0.70
unsafeMethod · 0.65
thenMethod · 0.45

Tested by

no test coverage detected