Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ const options = {
},
page: 2,
limit: 30,
order: 'name ASC'
order: 'name ASC',
useOrStatement: false
}

Animal.query(options)
Expand Down
9 changes: 9 additions & 0 deletions __tests__/BaseModel.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,5 +226,14 @@ describe('actions', () => {
expect(res).toEqual([])
})
})

it('find with or statement' , () => {
const options = { columns: '*', where: { nome_cont: '%Daniel%' } , useOrStatement: true }
return Tmp.query(options).then(res => {
expect(Tmp.repository.query).toHaveBeenCalledTimes(1)
expect(Tmp.repository.query).toBeCalledWith(options)
expect(res).toEqual([])
})
})
})
})
2 changes: 1 addition & 1 deletion src/BaseModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default class BaseModel {
}

/**
* @param {columns: '*', page: 1, limit: 30, where: {}, order: 'id DESC'} options
* @param {columns: '*', page: 1, limit: 30, where: {}, order: 'id DESC', useOrStatement: false } options
*/
static query(options) {
return this.repository.query(options)
Expand Down
14 changes: 9 additions & 5 deletions src/query_builder/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ const defaultOptions = {
page: null,
limit: 30,
where: {},
order: 'id DESC'
order: 'id DESC',
useOrStatement: false
}

// Creates the "SELECT" sql statement for find one record
Expand All @@ -18,12 +19,12 @@ export function find(tableName) {
* })
*/
export function query(tableName, options = {}) {
const { columns, page, limit, where, order } = {
const { columns, page, limit, where, order, useOrStatement } = {
...defaultOptions,
...options
}

const whereStatement = queryWhere(where)
const whereStatement = queryWhere(where, useOrStatement)
let sqlParts = [
'SELECT',
columns,
Expand Down Expand Up @@ -69,9 +70,12 @@ export function propertyOperation(statement) {
}

// Build where query
export function queryWhere(options) {
export function queryWhere(options, useOrStatement) {
let statement = findStatement(useOrStatement)
const list = Object.keys(options).map(p => `${propertyOperation(p)} ?`)
return list.length > 0 ? `WHERE ${list.join(' AND ')}` : ''
return list.length > 0 ? `WHERE ${list.join(statement)}` : ''
}

const findStatement = (useOrStatement) => useOrStatement ? ' OR ' : ' AND ';

export default { find, query }