Skip to content

Commit

Permalink
test: add tests for clone method
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Apr 2, 2020
1 parent d3584fe commit 6286276
Show file tree
Hide file tree
Showing 16 changed files with 384 additions and 14 deletions.
8 changes: 5 additions & 3 deletions adonis-typings/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,11 @@
*/

declare module '@ioc:Adonis/Lucid/Model' {
import knex from 'knex'
import { ProfilerContract, ProfilerRowContract } from '@ioc:Adonis/Core/Profiler'
import {
Update,
Counter,
Aggregate,
StrictValues,
QueryCallback,
ChainableContract,
SimplePaginatorContract,
ExcutableQueryBuilderContract,
Expand Down Expand Up @@ -185,6 +182,11 @@ declare module '@ioc:Adonis/Lucid/Model' {
*/
client: QueryClientContract

/**
* Clone query builder instance
*/
clone<ClonedResult = Result> (): ModelQueryBuilderContract<Model, ClonedResult>

/**
* A custom set of sideloaded properties defined on the query
* builder, this will be passed to the model instance created
Expand Down
1 change: 0 additions & 1 deletion adonis-typings/querybuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

declare module '@ioc:Adonis/Lucid/DatabaseQueryBuilder' {
import * as knex from 'knex'
import { ProfilerRowContract, ProfilerContract } from '@ioc:Adonis/Core/Profiler'
import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database'

/**
Expand Down
1 change: 1 addition & 0 deletions src/Orm/QueryBuilder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export class ModelQueryBuilder extends Chainable implements ModelQueryBuilderCon
public clone (): ModelQueryBuilder {
const clonedQuery = new ModelQueryBuilder(this.knexQuery.clone(), this.model, this.client)
this.applyQueryFlags(clonedQuery)
clonedQuery.sideloaded = Object.assign({}, this.sideloaded)
return clonedQuery
}

Expand Down
10 changes: 5 additions & 5 deletions src/Orm/Relations/Base/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ ModelConstructorContract
protected abstract profilerData (): any

/**
* The relationship query builder must implement this method
* to apply relationship related constraints
* Returns the sql query keys for the join query
*/
protected abstract applyConstraints (): void
protected abstract getRelationKeys (): string[]

/**
* Returns the sql query keys for the join query
* The relationship query builder must implement this method
* to apply relationship related constraints
*/
protected abstract getRelationKeys (): string[]
protected abstract applyConstraints (): void

/**
* Returns the name of the query action
Expand Down
4 changes: 3 additions & 1 deletion src/Orm/Relations/BelongsTo/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ ModelConstructorContract
* Applies constraint to limit rows to the current relationship
* only.
*/
public applyConstraints () {
protected applyConstraints () {
if (this.appliedConstraints) {
return
}
Expand Down Expand Up @@ -135,6 +135,8 @@ ModelConstructorContract
if (!['update', 'delete'].includes(queryAction)) {
this.limit(1)
}

return
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Orm/Relations/HasMany/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ ModelConstructorContract
* Applies constraint to limit rows to the current relationship
* only.
*/
public applyConstraints () {
protected applyConstraints () {
if (this.appliedConstraints) {
return
}
Expand Down
2 changes: 1 addition & 1 deletion src/Orm/Relations/HasManyThrough/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ ModelConstructorContract
* Applies constraint to limit rows to the current relationship
* only.
*/
public applyConstraints () {
protected applyConstraints () {
if (this.appliedConstraints) {
return
}
Expand Down
2 changes: 1 addition & 1 deletion src/Orm/Relations/HasOne/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ ModelConstructorContract
* Applies constraint to limit rows to the current relationship
* only.
*/
public applyConstraints () {
protected applyConstraints () {
if (this.appliedConstraints) {
return
}
Expand Down
3 changes: 2 additions & 1 deletion src/Orm/Relations/ManyToMany/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ ModelConstructorContract
* Applying query constraints to scope them to relationship
* only.
*/
public applyConstraints () {
protected applyConstraints () {
if (this.appliedConstraints) {
return
}
Expand Down Expand Up @@ -367,6 +367,7 @@ ModelConstructorContract
)

this.addWhereConstraints()
return
}

/**
Expand Down
36 changes: 36 additions & 0 deletions test/database/query-builder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8192,3 +8192,39 @@ test.group('Query Builder | paginate', (group) => {
await connection.disconnect()
})
})

test.group('Query Builder | clone', (group) => {
group.before(async () => {
await setup()
})

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

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

test('clone query builder', async (assert) => {
const connection = new Connection('primary', getConfig(), getLogger())
connection.connect()

let db = getQueryBuilder(getQueryClient(connection))

const clonedQuery = db.from('users').clone()
assert.deepEqual(clonedQuery, db)
await connection.disconnect()
})

test('copy internal to the cloned query builder', async (assert) => {
const connection = new Connection('primary', getConfig(), getLogger())
connection.connect()

let db = getQueryBuilder(getQueryClient(connection))

const clonedQuery = db.from('users').groupBy('id').clone()
assert.isTrue(clonedQuery.hasGroupBy)
await connection.disconnect()
})
})
49 changes: 49 additions & 0 deletions test/orm/model-belongs-to.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import test from 'japa'
import { BelongsTo } from '@ioc:Adonis/Lucid/Orm'

import { column, belongsTo } from '../../src/Orm/Decorators'
import { BelongsToQueryBuilder } from '../../src/Orm/Relations/BelongsTo/QueryBuilder'
import { ormAdapter, getBaseModel, setup, cleanup, resetTables, getDb, getProfiler } from '../../test-helpers'

let db: ReturnType<typeof getDb>
Expand Down Expand Up @@ -1208,3 +1209,51 @@ test.group('Model | BelongsTo | bulk operations', (group) => {
}
})
})

test.group('Model | BelongsTo | clone', (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('clone related query builder', async (assert) => {
class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public username: string
}
User.boot()

class Profile extends BaseModel {
@column()
public userId: number

@column()
public displayName: string

@belongsTo(() => User)
public user: BelongsTo<User>
}
Profile.boot()

await db.insertQuery().table('users').insert({ username: 'virk' })
await db.insertQuery().table('profiles').insert({ display_name: 'Hvirk', user_id: 1 })

const profile = await Profile.findOrFail(1)

const clonedQuery = profile.related('user').query().clone()
assert.instanceOf(clonedQuery, BelongsToQueryBuilder)
})
})
83 changes: 83 additions & 0 deletions test/orm/model-has-many-through.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import test from 'japa'
import { HasManyThrough } from '@ioc:Adonis/Lucid/Orm'

import { hasManyThrough, column } from '../../src/Orm/Decorators'
import { HasManyThroughQueryBuilder } from '../../src/Orm/Relations/HasManyThrough/QueryBuilder'
import { ormAdapter, getBaseModel, setup, cleanup, resetTables, getDb, getProfiler } from '../../test-helpers'

let db: ReturnType<typeof getDb>
Expand Down Expand Up @@ -1352,3 +1353,85 @@ test.group('Model | Has Many Through | pagination', (group) => {
}
})
})

test.group('Model | Has Many Through | clone', (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('clone related model query builder', async (assert) => {
class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@column()
public countryId: number
}
User.boot()

class Post extends BaseModel {
@column()
public userId: number
}
Post.boot()

class Country extends BaseModel {
@column({ isPrimary: true })
public id: number

@hasManyThrough([() => Post, () => User])
public posts: HasManyThrough<Post>
}
Country.boot()

await db.table('countries').multiInsert([{ name: 'India' }, { name: 'Switzerland' }])
await db.table('users').multiInsert([
{
username: 'virk',
country_id: 1,
},
{
username: 'nikk',
country_id: 1,
},
{
username: 'romain',
country_id: 2,
},
])

await db.table('posts').multiInsert([
{
title: 'Adonis 101',
user_id: 1,
},
{
title: 'Lucid 101',
user_id: 1,
},
{
title: 'Design 101',
user_id: 2,
},
{
title: 'Dev 101',
user_id: 3,
},
])

const country = await Country.find(1)
const clonedQuery = country!.related('posts').query().clone()
assert.instanceOf(clonedQuery, HasManyThroughQueryBuilder)
})
})
44 changes: 44 additions & 0 deletions test/orm/model-has-many.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import test from 'japa'
import { HasMany } from '@ioc:Adonis/Lucid/Orm'

import { column, hasMany } from '../../src/Orm/Decorators'
import { HasManyQueryBuilder } from '../../src/Orm/Relations/HasMany/QueryBuilder'

import {
setup,
getDb,
Expand Down Expand Up @@ -1826,3 +1828,45 @@ test.group('Model | HasMany | paginate', (group) => {
}
})
})

test.group('Model | HasMany | clone', (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('clone related model query builder', async (assert) => {
class Post extends BaseModel {
@column()
public userId: number
}

class User extends BaseModel {
@column({ isPrimary: true })
public id: number

@hasMany(() => Post)
public posts: HasMany<Post>
}

User.boot()
User.$getRelation('posts').boot()

const [ userId ] = await db.table('users').insert({ username: 'virk' }).returning('id')
await db.table('posts').multiInsert(getPosts(18, userId))

const user = await User.find(1)
const clonedQuery = user!.related('posts').query().clone()
assert.instanceOf(clonedQuery, HasManyQueryBuilder)
})
})
Loading

0 comments on commit 6286276

Please sign in to comment.