Skip to content

Commit

Permalink
fix: do not wrap aggregates result into model instances
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Feb 8, 2020
1 parent 81e7972 commit b7dbf6b
Show file tree
Hide file tree
Showing 9 changed files with 161 additions and 28 deletions.
12 changes: 12 additions & 0 deletions adonis-typings/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ declare module '@ioc:Adonis/Lucid/Model' {
import {
Update,
Counter,
Aggregate,
StrictValues,
QueryCallback,
ChainableContract,
Expand Down Expand Up @@ -195,6 +196,17 @@ declare module '@ioc:Adonis/Lucid/Model' {
* Define relationships to be preloaded
*/
preload: QueryBuilderPreloadFn<InstanceType<Model>, this>

/**
* Aggregates
*/
count: Aggregate<ModelQueryBuilderContract<Model, any>>
countDistinct: Aggregate<ModelQueryBuilderContract<Model, any>>
min: Aggregate<ModelQueryBuilderContract<Model, any>>
max: Aggregate<ModelQueryBuilderContract<Model, any>>
sum: Aggregate<ModelQueryBuilderContract<Model, any>>
avg: Aggregate<ModelQueryBuilderContract<Model, any>>
avgDistinct: Aggregate<ModelQueryBuilderContract<Model, any>>
}

/**
Expand Down
22 changes: 11 additions & 11 deletions adonis-typings/querybuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,17 +578,6 @@ declare module '@ioc:Adonis/Lucid/DatabaseQueryBuilder' {

skipLocked (): this
noWait (): this

/**
* Aggregates
*/
count: Aggregate<this>
countDistinct: Aggregate<this>
min: Aggregate<this>
max: Aggregate<this>
sum: Aggregate<this>
avg: Aggregate<this>
avgDistinct: Aggregate<this>
}

/**
Expand Down Expand Up @@ -632,6 +621,17 @@ declare module '@ioc:Adonis/Lucid/DatabaseQueryBuilder' {
update: Update<this>
increment: Counter<this>
decrement: Counter<this>

/**
* Aggregates
*/
count: Aggregate<this>
countDistinct: Aggregate<this>
min: Aggregate<this>
max: Aggregate<this>
sum: Aggregate<this>
avg: Aggregate<this>
avgDistinct: Aggregate<this>
}

/**
Expand Down
62 changes: 62 additions & 0 deletions src/Orm/QueryBuilder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,68 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon
return this
}

/**
* Count rows for the current query
*/
public count (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
return super.count(columns, alias)
}

/**
* Count distinct rows for the current query
*/
public countDistinct (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.countDistinct(columns, alias)
return this
}

/**
* Make use of `min` aggregate function
*/
public min (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.min(columns, alias)
return this
}

/**
* Make use of `max` aggregate function
*/
public max (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.max(columns, alias)
return this
}

/**
* Make use of `avg` aggregate function
*/
public avg (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.avg(columns, alias)
return this
}

/**
* Make use of distinct `avg` aggregate function
*/
public avgDistinct (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.avgDistinct(columns, alias)
return this
}

/**
* Make use of `sum` aggregate function
*/
public sum (columns: any, alias?: any): this {
this.wrapResultsToModelInstances = false
super.sum(columns, alias)
return this
}

/**
* Executes the query
*/
Expand Down
34 changes: 21 additions & 13 deletions test/orm/base-model-options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@ import { Profiler } from '@adonisjs/profiler/build/standalone'
import { HasOne } from '@ioc:Adonis/Lucid/Relations'

import { column, hasOne } from '../../src/Orm/Decorators'
import { setup, cleanup, getDb, resetTables, getBaseModel, ormAdapter } from '../../test-helpers'
import {
setup,
getDb,
cleanup,
ormAdapter,
getProfiler,
resetTables,
getBaseModel,
} from '../../test-helpers'

let db: ReturnType<typeof getDb>
let BaseModel: ReturnType<typeof getBaseModel>
Expand Down Expand Up @@ -173,7 +181,7 @@ test.group('Model options | Adapter', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const user = await User.query({ profiler }).first()
assert.equal(user!.options!.connection, 'primary')
Expand Down Expand Up @@ -266,7 +274,7 @@ test.group('Model options | Model.find', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const user = await User.find(1, { profiler })
assert.deepEqual(user!.options!.profiler, profiler)
Expand Down Expand Up @@ -339,7 +347,7 @@ test.group('Model options | Model.findOrFail', (group) => {

const customDb = getDb()
await customDb.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const user = await User.findOrFail(1, { profiler })
assert.deepEqual(user.options!.profiler, profiler)
Expand Down Expand Up @@ -411,7 +419,7 @@ test.group('Model options | Model.findMany', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const users = await User.findMany([1], { profiler })
assert.deepEqual(users[0].options!.profiler, profiler)
Expand Down Expand Up @@ -507,7 +515,7 @@ test.group('Model options | Model.firstOrCreate', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const user = await User.firstOrCreate({ username: 'virk' }, undefined, { profiler })
const total = await db.from('users').count('*', 'total')
Expand All @@ -529,7 +537,7 @@ test.group('Model options | Model.firstOrCreate', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const user = await User.firstOrCreate({ username: 'nikk' }, undefined, { profiler })
const total = await db.from('users').count('*', 'total')
Expand Down Expand Up @@ -708,7 +716,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const [user] = await User.fetchOrCreateMany(
'username',
Expand All @@ -734,7 +742,7 @@ test.group('Model options | Model.fetchOrCreateMany', (group) => {
public username: string
}

const profiler = new Profiler({})
const profiler = getProfiler()
const [user] = await User.fetchOrCreateMany(
'username',
[{ username: 'virk' }],
Expand Down Expand Up @@ -947,7 +955,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => {
}

await db.insertQuery().table('users').insert({ username: 'virk' })
const profiler = new Profiler({})
const profiler = getProfiler()

const [user] = await User.updateOrCreateMany(
'username',
Expand All @@ -973,7 +981,7 @@ test.group('Model options | Model.updateOrCreateMany', (group) => {
public username: string
}

const profiler = new Profiler({})
const profiler = getProfiler()
const [user] = await User.updateOrCreateMany(
'username',
[{ username: 'virk' }],
Expand Down Expand Up @@ -1225,7 +1233,7 @@ test.group('Model options | Query Builder Preloads', (group) => {
await db.insertQuery().table('users').insert({ username: 'virk' })
await db.insertQuery().table('profiles').insert({ user_id: 1, display_name: 'Virk' })

const profiler = new Profiler({})
const profiler = getProfiler()
const users = await User.query({ profiler }).preload('profile').exec()

assert.lengthOf(users, 1)
Expand Down Expand Up @@ -1471,7 +1479,7 @@ test.group('Model options | Model Preloads', (group) => {
await db.insertQuery().table('users').insert({ username: 'virk' })
await db.insertQuery().table('profiles').insert({ user_id: 1, display_name: 'Virk' })

const profiler = new Profiler({})
const profiler = getProfiler()
const user = await User.query({ profiler }).firstOrFail()

assert.equal(user.options!.connection, 'primary')
Expand Down
51 changes: 51 additions & 0 deletions test/orm/base-model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3354,3 +3354,54 @@ test.group('Base model | extend', (group) => {
assert.deepEqual(bindings, knexBindings)
})
})

test.group('Base Model | aggregates', (group) => {
group.before(async () => {
db = getDb()
BaseModel = getBaseModel(ormAdapter(db))
await setup()
})

group.after(async () => {
await cleanup()
await db.manager.closeAll()
})

group.afterEach(async () => {
await resetTables()
})

test('count *', async (assert) => {
class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public username: string

@column()
public email: string
}

await db.insertQuery().table('users').multiInsert([{ username: 'virk' }, { username: 'nikk' }])
const usersCount = await User.query().count('* as total')
assert.deepEqual(usersCount, [{ total: 2 }])
})

test('count * distinct', async (assert) => {
class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public username: string

@column()
public email: string
}

await db.insertQuery().table('users').multiInsert([{ username: 'virk' }, { username: 'nikk' }])
const usersCount = await User.query().countDistinct('username as total')
assert.deepEqual(usersCount, [{ total: 2 }])
})
})
2 changes: 1 addition & 1 deletion test/orm/model-has-many-through.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ test.group('Model | Has Many Through | preload', (group) => {
const profiler = getProfiler(true)

let profilerPacketIndex = 0
profiler.subscribe((packet) => {
profiler.process((packet) => {
if (profilerPacketIndex === 1) {
assert.deepEqual(packet.data.relation, {
model: 'Country',
Expand Down
2 changes: 1 addition & 1 deletion test/orm/model-has-many.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1013,7 +1013,7 @@ test.group('Model | HasMany | preload', (group) => {
const profiler = getProfiler(true)

let profilerPacketIndex = 0
profiler.subscribe((packet) => {
profiler.process((packet) => {
if (profilerPacketIndex === 1) {
assert.deepEqual(packet.data.relation, { model: 'User', relatedModel: 'Post', relation: 'hasMany' })
}
Expand Down
2 changes: 1 addition & 1 deletion test/orm/model-has-one.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1148,7 +1148,7 @@ test.group('Model | HasOne | preload', (group) => {
const profiler = getProfiler(true)

let profilerPacketIndex = 0
profiler.subscribe((packet) => {
profiler.process((packet) => {
if (profilerPacketIndex === 1) {
assert.deepEqual(packet.data.relation, { model: 'User', relatedModel: 'Profile', relation: 'hasOne' })
}
Expand Down
2 changes: 1 addition & 1 deletion test/orm/model-many-to-many.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1266,7 +1266,7 @@ test.group('Model | ManyToMany | wherePivot', (group) => {
const profiler = getProfiler(true)

let profilerPacketIndex = 0
profiler.subscribe((packet) => {
profiler.process((packet) => {
if (profilerPacketIndex === 1) {
assert.deepEqual(packet.data.relation, {
model: 'User',
Expand Down

0 comments on commit b7dbf6b

Please sign in to comment.