Skip to content

Instantly share code, notes, and snippets.

@mzibari
Created July 4, 2020 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzibari/eba5db6b98f20cd3710832923eff0d48 to your computer and use it in GitHub Desktop.
Save mzibari/eba5db6b98f20cd3710832923eff0d48 to your computer and use it in GitHub Desktop.
DROP TYPE IF EXISTS grocery;
CREATE TYPE grocery AS ENUM (
'Main',
'Snack',
'Lunch',
'Breakfast'
);
CREATE TABLE IF NOT EXISTS shopping_list (
id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
name TEXT NOT NULL,
price INTEGER(2) NOT NULL,
date_added TIMESTAMP DEFAULT now() NOT NULL,
checked BOOLEAN DEFAULT FALSE NOT NULL,
category grocery NOT NULL
)
const knex = require('knex');
require('dotenv').config();
const knexInstance = knex({
client: 'pg',
connection: process.env.DB_URL
})
function searchName(searchTerm) {
knexInstance
.select('name')
.from('shopping_list')
.where('name', 'ILIKE', `%${searchTerm}%`)
.then(results => {
console.log(results);
});
}
const search = 'phony';
searchName(search);
function paginateProducts(page) {
const productsPerPage = 6
const offset = productsPerPage * (page - 1)
knexInstance
.select('id', 'name', 'price', 'date_added', 'checked', 'category')
.from('shopping_list')
.limit(productsPerPage)
.offset(offset)
.then(result => {
console.log('Paginated')
console.log(result)
})
}
paginateProducts(2)
function sinceDate(daysAgo) {
knexInstance
.select('id', 'name', 'price', 'date_added', 'checked', 'category')
.from('shopping_list')
.where('date_added', '>', daysAgo)
.then(results => {
console.log('Days Ago')
console.log(results)
})
}
sinceDate('2020-06-23T22:19:20.407Z')
function costPerCategory() {
knexInstance
.select('category')
.sum('price as total')
.from('shopping_list')
.groupBy('category')
.then(result => {
console.log('COST PER CATEGORY')
console.log(result)
})
}
costPerCategory()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment