Skip to content

Instantly share code, notes, and snippets.

View koskimas's full-sized avatar

Sami Koskimäki koskimas

View GitHub Profile
insert into "person" (id, first_name, last_name)
values ($1, $2, $3)
on conflict ("id") do nothing
db.insertInto('person')
.values(person)
.onConflictDoNothing('id')
with "species_ages" as (
select "species",
min("pet"."age") as "min_age",
max("pet"."age") as "max_age"
from "pet"
group by "species"
)
select "max_age"
from "species_ages", (
select "species", count("toy"."id") as "num_toys"
await Person.query()
.joinRelated('children(isFemale, hasPets, isJennifer)')
.modifiers({
hasPets(query: QueryBuilder<Person>): void {
query.whereExists(Person.relatedQuery('pets'))
},
isJennifer(query: QueryBuilder<Person>): void {
query.modify('findByName', 'Jennifer')
}
await Person.query()
.withGraphFetched('children(isFemale, hasPets, isJennifer)')
.modifiers({
// New query-local modifier
hasPets(query: QueryBuilder<Person>): void {
query.whereExists(Person.relatedQuery('pets'))
},
// Bind argument to existing modifier.
isJennifer(query: QueryBuilder<Person>): void {
// Modifiers can be used with any query.
await Person.query().modify('findByName', fullName)
// Modifiers can be used with eager loading.
await Person.query().withGraphFetched('children(isFemale)')
class Person extends Model {
static modifiers = {
isFemale(query: QueryBuilder<Person>): void {
query.where('gender', 'female')
},
findByName(query: QueryBuilder<Person>, name: string): void {
const { ref, fn } = Person
const { lower } = fn
class Person extends Model {
static async beforeDelete({
asFindQuery,
cancelQuery
}: StaticHookArguments<Person>): Promise<any> {
const idsOfPersonsAboutToBeDeleted = await asFindQuery().select('id')
if (!(await shouldDelete(idsOfPersonsAboutToBeDeleted))) {
cancelQuery()
}
// Note that the following query isn't executed! There's no `await`.
const jennifers = Actor.query().where('firstName', 'Jennifer')
// This is the only query that gets executed. `jennifers` query is built into
// the SQL as a subquery.
const movies = await Actor.relatedQuery('movies')
.for(jennifers)
.where('genre', 'action')
// Note that the following query isn't executed! There's no `await`.
const finnishActorsThatHaveChildren = Actor.query()
.where('nationality', 'finnish')
.whereExists(Actor.relatedQuery('children'))
// This is the only query that gets executed. `finnishActorsThatHaveChildren`
// query is built into the SQL as a subquery.
await Actor.relatedQuery('movies')
.for(finnishActorsThatHaveChildren)
.unrelate()