Skip to content

Commit

Permalink
Merge branch 'release/4.0.24'
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Nov 22, 2017
2 parents 7fc636d + 2f5aa45 commit baa5f64
Show file tree
Hide file tree
Showing 21 changed files with 1,002 additions and 127 deletions.
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
<a name="4.0.24"></a>
## [4.0.24](https://github.com/adonisjs/adonis-lucid/compare/v4.0.23...v4.0.24) (2017-11-22)


### Bug Fixes

* **lucid:** on save retain timestamps inside memory ([4f0c035](https://github.com/adonisjs/adonis-lucid/commit/4f0c035)), closes [#235](https://github.com/adonisjs/adonis-lucid/issues/235)
* **relations:** changed method _normalizeRelations ([b085f8a](https://github.com/adonisjs/adonis-lucid/commit/b085f8a))
* **relations:** parse relations array ([3cea702](https://github.com/adonisjs/adonis-lucid/commit/3cea702))
* **test:** remove followers table on tear down ([fe69ed2](https://github.com/adonisjs/adonis-lucid/commit/fe69ed2))
* **tests:** test fixes for postgresql ([27ac971](https://github.com/adonisjs/adonis-lucid/commit/27ac971))


### Features

* **database:** add aggregation helpers ([10023f7](https://github.com/adonisjs/adonis-lucid/commit/10023f7))
* **lucid:** add afterPaginate hook ([f12d8a5](https://github.com/adonisjs/adonis-lucid/commit/f12d8a5)), closes [#236](https://github.com/adonisjs/adonis-lucid/issues/236)
* **lucid:** add Model.truncate() function ([#240](https://github.com/adonisjs/adonis-lucid/issues/240)) ([9be15a9](https://github.com/adonisjs/adonis-lucid/commit/9be15a9))
* **migrations:** introduce a silent flag to silent the output ([c16abb8](https://github.com/adonisjs/adonis-lucid/commit/c16abb8))
* **query-builder:** add last method ([#232](https://github.com/adonisjs/adonis-lucid/issues/232)) ([01a6fa7](https://github.com/adonisjs/adonis-lucid/commit/01a6fa7))



<a name="4.0.23"></a>
## [4.0.23](https://github.com/adonisjs/adonis-lucid/compare/v4.0.22...v4.0.23) (2017-11-13)

Expand Down
15 changes: 15 additions & 0 deletions commands/BaseMigration.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ class BaseMigration extends Command {
throw new Error('Cannot run migrations in production. Use --force flag to continue')
}
}

/**
* Executes the function when conditional
* is false
*
* @method execIfNot
*
* @param {Boolean} conditional
* @param {Function} fn
*/
execIfNot (conditional, fn) {
if (!conditional) {
fn()
}
}
}

module.exports = BaseMigration
8 changes: 5 additions & 3 deletions commands/MigrationRefresh.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class MigrationRefresh extends BaseMigration {
return `
migration:refresh
{ -f, --force: Forcefully run migrations in production }
{ -s, --silent: Silent the migrations output }
{ --log: Log SQL queries instead of executing them }
`
}
Expand All @@ -50,13 +51,14 @@ class MigrationRefresh extends BaseMigration {
* @param {Object} args
* @param {Boolean} options.log
* @param {Boolean} options.force
* @param {Boolean} options.silent
*
* @return {void|Array}
*/
async handle (args, { log, force }) {
async handle (args, { log, force, silent }) {
this._validateState(force)
await ace.call('migration:reset', {}, { log, force })
await ace.call('migration:run', {}, { log, force })
await ace.call('migration:reset', {}, { log, force, silent })
await ace.call('migration:run', {}, { log, force, silent })
}
}

Expand Down
12 changes: 7 additions & 5 deletions commands/MigrationReset.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class MigrationReset extends BaseMigration {
return `
migration:reset
{ -f, --force: Forcefully run migrations in production }
{ -s, --silent: Silent the migrations output }
{ --log: Log SQL queries instead of executing them }
`
}
Expand All @@ -50,10 +51,11 @@ class MigrationReset extends BaseMigration {
* @param {Object} args
* @param {Boolean} options.log
* @param {Boolean} options.force
* @param {Boolean} options.silent
*
* @return {void|Array}
*/
async handle (args, { log, force }) {
async handle (args, { log, force, silent }) {
try {
this._validateState(force)

Expand All @@ -64,15 +66,15 @@ class MigrationReset extends BaseMigration {
* Tell user that there is nothing to migrate
*/
if (status === 'skipped') {
this.info('Already at the last batch')
this.execIfNot(silent, () => this.info('Already at the last batch'))
}

/**
* Log files that been migrated successfully
*/
if (status === 'completed' && !queries) {
const endTime = process.hrtime(startTime)
migrated.forEach((name) => this.completed('rollback', `${name}.js`))
migrated.forEach((name) => this.execIfNot(silent, () => this.completed('rollback', `${name}.js`)))
this.success(`Reset completed in ${prettyHrTime(endTime)}`)
}

Expand All @@ -81,8 +83,8 @@ class MigrationReset extends BaseMigration {
*/
if (queries) {
_.each(queries, ({queries, name}) => {
console.log(this.chalk.magenta(`\n Queries for ${name}.js`))
_.each(queries, (query) => console.log(` ${query}`))
this.execIfNot(silent, () => console.log(this.chalk.magenta(`\n Queries for ${name}.js`)))
_.each(queries, (query) => this.execIfNot(silent, () => console.log(` ${query}`)))
console.log('\n')
})
}
Expand Down
12 changes: 7 additions & 5 deletions commands/MigrationRollback.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class MirationRollback extends BaseMigration {
migration:rollback
{ -b, --batch=@value: Rollback upto a specific batch number }
{ -f, --force: Forcefully run migrations in production }
{ -s, --silent: Silent the migrations output }
{ --log: Log SQL queries instead of executing them }
`
}
Expand All @@ -52,10 +53,11 @@ class MirationRollback extends BaseMigration {
* @param {Boolean} options.log
* @param {Boolean} options.force
* @param {Number} options.batch
* @param {Boolean} options.silent
*
* @return {void|Array}
*/
async handle (args, { log, force, batch }) {
async handle (args, { log, force, batch, silent }) {
try {
batch = batch ? Number(batch) : null

Expand All @@ -68,15 +70,15 @@ class MirationRollback extends BaseMigration {
* Tell user that there is nothing to migrate
*/
if (status === 'skipped') {
this.info('Already at the last batch')
this.execIfNot(silent, () => this.info('Already at the last batch'))
}

/**
* Log files that been migrated successfully
*/
if (status === 'completed' && !queries) {
const endTime = process.hrtime(startTime)
migrated.forEach((name) => this.completed('rollback', `${name}.js`))
migrated.forEach((name) => this.execIfNot(silent, () => this.completed('rollback', `${name}.js`)))
this.success(`Rollback completed in ${prettyHrTime(endTime)}`)
}

Expand All @@ -85,8 +87,8 @@ class MirationRollback extends BaseMigration {
*/
if (queries) {
_.each(queries, ({queries, name}) => {
console.log(this.chalk.magenta(`\n Queries for ${name}.js`))
_.each(queries, (query) => console.log(` ${query}`))
this.execIfNot(silent, () => console.log(this.chalk.magenta(`\n Queries for ${name}.js`)))
_.each(queries, (query) => this.execIfNot(silent, () => console.log(` ${query}`)))
console.log('\n')
})
}
Expand Down
14 changes: 9 additions & 5 deletions commands/MigrationRun.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class MigrationRun extends BaseMigration {
return `
migration:run
{ -f, --force: Forcefully run migrations in production }
{ -s, --silent: Silent the migrations output }
{ --log: Log SQL queries instead of executing them }
`
}
Expand All @@ -49,10 +50,12 @@ class MigrationRun extends BaseMigration {
*
* @param {Object} args
* @param {Boolean} options.log
* @param {Boolean} options.force
* @param {Boolean} options.silent
*
* @return {void|Array}
*/
async handle (args, { log, force }) {
async handle (args, { log, force, silent }) {
try {
this._validateState(force)

Expand All @@ -63,15 +66,15 @@ class MigrationRun extends BaseMigration {
* Tell user that there is nothing to migrate
*/
if (status === 'skipped') {
this.info('Nothing to migrate')
this.execIfNot(silent, () => this.info('Nothing to migrate'))
}

/**
* Log files that been migrated successfully
*/
if (status === 'completed' && !queries) {
const endTime = process.hrtime(startTime)
migrated.forEach((name) => this.completed('migrate', `${name}.js`))
migrated.forEach((name) => this.execIfNot(silent, () => this.completed('migrate', `${name}.js`)))
this.success(`Database migrated successfully in ${prettyHrTime(endTime)}`)
}

Expand All @@ -80,8 +83,8 @@ class MigrationRun extends BaseMigration {
*/
if (queries) {
_.each(queries, ({queries, name}) => {
console.log(this.chalk.magenta(`\n Queries for ${name}.js`))
_.each(queries, (query) => console.log(` ${query}`))
this.execIfNot(silent, () => console.log(this.chalk.magenta(`\n Queries for ${name}.js`)))
_.each(queries, (query) => this.execIfNot(silent, () => console.log(` ${query}`)))
console.log('\n')
})
}
Expand All @@ -91,6 +94,7 @@ class MigrationRun extends BaseMigration {
}
} catch (error) {
console.log(error)
process.exit(1)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adonisjs/lucid",
"version": "4.0.23",
"version": "4.0.24",
"description": "SQL ORM built on top of Active Record pattern",
"main": "index.js",
"scripts": {
Expand Down
149 changes: 149 additions & 0 deletions src/Database/MonkeyPatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,152 @@ KnexQueryBuilder.prototype.paginate = async function (page = 2, perPage = 20) {
data: data
}
}

/**
* Generates an aggregate function, that returns the aggregated result
* as a number.
*
* @method generateAggregate
*
* @param {String} aggregateOp
* @param {String} defaultColumnName
*
* @return {Number}
*
* @example
* ```js
* generateAggregate('count')
* ```
*/
function generateAggregate (aggregateOp, defaultColumnName = undefined) {
let funcName = `get${_.upperFirst(aggregateOp)}`

/**
* Do not re-add the method if exists
*/
if (KnexQueryBuilder.prototype[funcName]) {
return
}

KnexQueryBuilder.prototype[funcName] = async function (columnName = defaultColumnName) {
if (!columnName) {
throw new Error(`'${funcName}' requires a column name.`)
}

const wrapper = new this.constructor(this.client)
const query = wrapper.from(this.as('__lucid'))[aggregateOp](`${columnName} as __lucid_aggregate`)
const results = await query
return results[0].__lucid_aggregate
}
}

/**
* Fetch and return a row count
*
* @method getCount
* @async
*
* @param {String} columnName = '*'
*
* @return {Number} The count of of rows in this query
*/
generateAggregate('count', '*')

/**
* Fetch and return a distinct row count
*
* @method getCountDistinct
* @async
*
* @param {String} columnName
*
* @return {Number} The distinct count of rows in this query
*/
generateAggregate('countDistinct')

/**
* Fetch and return the sum of all values in columnName
*
* @method getSum
* @async
*
* @param {String} columnName
*
* @return {Number} The sum of columnName
*/
generateAggregate('sum')

/**
* Fetch and return the sum of all distinct values in columnName
*
* @method getSumDistinct
* @async
*
* @param {String} columnName
*
* @return {Number} The sum of distinct values in columnName
*/
generateAggregate('sumDistinct')

/**
* Fetch and return the minimum of all values in columnName
*
* @method getMin
* @async
*
* @param {String} columnName
*
* @return {Number} The minimunm value of columnName
*/
generateAggregate('min')

/**
* Fetch and return the maximum of all values in columnName
*
* @method getMax
* @async
*
* @param {String} columnName
*
* @return {Number} The maximunm value of columnName
*/
generateAggregate('max')

/**
* Fetch and return the average of all values in columnName
*
* @method getAvg
* @async
*
* @param {String} columnName
*
* @return {Number} The average value of columnName
*/
generateAggregate('avg')

/**
* Fetch and return the average of all distinct values in columnName
*
* @method getAvgDistinct
* @async
*
* @param {String} columnName
*
* @return {Number} The average of distinct values of columnName
*/
generateAggregate('avgDistinct')

/**
* Returns the latest row from the database.
*
* @method last
*
* @for Database
*
* @param {string} [field = 'id']
*
* @chainable
*/
KnexQueryBuilder.prototype.last = async function (field = 'id') {
return this.orderBy(field, 'desc').first()
}
Loading

0 comments on commit baa5f64

Please sign in to comment.