Commit e5097598 authored by Clara Stoddart's avatar Clara Stoddart

Sql-js installed

parent 99d64ad1
......@@ -2,7 +2,7 @@
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited_true';
var MOUSE_VISITED_CLASSNAME_FALSE = 'crx_mouse_visited_false';
var worker = new Worker("./sql.js/dist/worker.sql-wasm.js");
var srcName;
// var requestResult;
......@@ -16,15 +16,10 @@ function dietNumInit() {
dietNum = a + (b << 1) + (c << 2) + (d << 3);
}
// https://github.com/sql-js/sql.js/blob/master/examples/GUI/gui.js
function databaseInit() {
}
function queryDatabase(product) {
}
// function initialise() {
// var db = new SQL.Database(public.db);
//
// }
// function query(product) {
// const sqlite3 = require('sqlite3').verbose();
......@@ -34,15 +29,15 @@ function queryDatabase(product) {
// console.error('Error connecting to database');
// }
// console.log('Connected to the in-memory SQlite database.');
// });
// });
// let sql = `SELECT Containsdairy cd,
// let sql = `SELECT Containsdairy cd,
// Containsmeat cm,
// Containscorn cc,
// Containsgluten cg
// FROM productsIngredients
// Containscorn cc,
// Containsgluten cg
// FROM productsIngredients
// WHERE Product = ?`;
// db.get(sql, product, (err, row) => {
......@@ -102,6 +97,51 @@ function queryDatabase(product) {
// return result;
// }
// function checkAllergen(product) {
// var xhr = new XMLHttpRequest();
// var result;
// xhr.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// var canEat = this.responseText;
// if (canEat == undefined) {
// result = false;
// } else if (canEat == "0") {
// result = false;
// } else if (canEat == "1") {
// result = true;
// } else if (canEat == "Could not connect") {
// result = false;
// }
// }
// };
// xhr.open("GET", "script.php?q="+product, true);
// xhr.send();
// return result;
// }
//
function checkAllergen(product) {
var db = new SQL.Database();
var sqlstr = "CREATE TABLE productsingredients (product character varying(255), containsgluten boolean, containsdairy boolean, containscorn boolean, containsmeat boolean);";
sqlstr += "INSERT INTO productsingredients VALUES ('6 Chocolate Fairy Cakes', true, true, true, false);"
db.run(sqlstr);
let sql = `SELECT containsdairy cd,
containsmeat cm,
containscorn cc,
containsgluten cg
FROM productsIngredients
WHERE product=:prod`;
// WHERE Product = ` + product
var stmt = db.prepare(sql);
var result = stmt.getAsObject({':prod' : product});
console.log(result);
return !((cd && (1 && dietNum)) || (cm && (2 && dietNum)) || (cc && (4 && dietNum)) || (cg && (8 && dietNum)));
}
// Previous dom, that we want to track, so we can remove the previous styling.
//var prevDOM = null;
......@@ -125,10 +165,11 @@ document.addEventListener('mousemove', function (e) {
// srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
// }
// currName = srcElement.srcName;
if (true) {
var canEat = checkAllergen('6 Chocolate Fairy Cakes');
if (canEat) {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME); //changes outline of pic
}
if (!true) {
if (!canEat) {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME_FALSE);
}
//TODO: modify behaviour according to different allergens
......
{
"presets": ["es2015"]
}
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
language: node_js
node_js:
- '6'
before_install:
- 'npm install'
MIT License
Copyright (c) 2016 Alejandro Martin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[![Version](https://img.shields.io/badge/Version-0.0.1-blue.svg)](https://img.shields.io/badge/Version-0.0.1-blue.svg)
[![Build Status](https://travis-ci.org/alex030293/sqljs.svg?branch=master)](https://travis-ci.org/alex030293/sqljs)
# SQLjs
SQL-like interface for JavaScript
# Usage
## Trivial
```javascript
import { query } from 'sql-js';
const characters = [
{ name: 'Han', profession: 'Smuggler', age: 30 },
{ name: 'Luke', profession: 'Hero', age: 32 },
{ name: 'Leia', profession: 'Princess', age: 32 },
{ name: 'Anakin', profession: 'Jedi', age: 50 },
{ name: 'Obi', profession: 'Jedi', age: 65 },
{ name: 'Chewie', profession: 'Smuggler', age: 30 },
{ name: 'Lando', profession: 'Smuggler', age: 50 }
];
let resultSet = query()
.select()
.from(characters)
.execute();
```
## The easy way
```javascript
import { query } from 'sql-js';
const characters = [
{ name: 'Han', profession: 'Smuggler', age: 30 },
{ name: 'Luke', profession: 'Hero', age: 32 },
{ name: 'Leia', profession: 'Princess', age: 32 },
{ name: 'Anakin', profession: 'Jedi', age: 50 },
{ name: 'Obi', profession: 'Jedi', age: 65 },
{ name: 'Chewie', profession: 'Smuggler', age: 30 },
{ name: 'Lando', profession: 'Smuggler', age: 50 }
];
const isJedi = (person) => person.profession === 'Jedi';
const age = (character) => character.age;
let resultSet = query()
.select()
.from(characters)
.where(isJedi)
.groupBy(age)
.execute();
```
## Level Up
```javascript
import { query } from 'sql-js';
const rebels = [
{ name: 'Han', profession: 'Smuggler', age: 30 },
{ name: 'Luke', profession: 'Jedi', age: 32, father: 'Darth Vader' },
{ name: 'Leia', profession: 'Princess', age: 32 },
{ name: 'Obi', profession: 'Jedi', age: 65 },
{ name: 'Chewie', profession: 'Smuggler', age: 30 }
];
const empire = [
{ name: 'Anakin', profession: 'Jedi', age: 50 },
{ name: 'Darth Vader', profession: 'Lord Sith', age: 65 },
{ name: 'Lando', profession: 'Smuggler', age: 50 }
];
const fatherJoin = (join) => join[0].father === join[1].name;
const isJedi = (join) => join[0].profession === 'Jedi';
const age = (join) => join[0].age;
const older20 = (group) => group[0] > 20;
let resultSet = query()
.select()
.from(rebels, empire)
.where(fatherJoin)
.where(isJedi)
.groupBy(age)
.having(older20)
.execute();
```
import query from 'sqljs';
const rebels = [
{ name: 'Han', profession: 'Smuggler', age: 30 },
{ name: 'Luke', profession: 'Jedi', age: 32, father: 'Darth Vader' },
{ name: 'Leia', profession: 'Princess', age: 32 },
{ name: 'Obi', profession: 'Jedi', age: 65 },
{ name: 'Chewie', profession: 'Smuggler', age: 30 }
];
const empire = [
{ name: 'Anakin', profession: 'Jedi', age: 50 },
{ name: 'Darth Vader', profession: 'Lord Sith', age: 65 },
{ name: 'Lando', profession: 'Smuggler', age: 50 }
];
const fatherJoin = (join) => join[0].father === join[1].name;
const isJedi = (join) => join[0].profession === 'Jedi';
const age = (join) => join[0].age;
const older20 = (group) => group[0] > 20;
let resultSet = query()
.select()
.from(rebels, empire)
.where(fatherJoin)
.where(isJedi)
.groupBy(age)
.having(older20)
.execute();
console.log(JSON.stringify(resultSet));
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var query = function query() {
var status = arguments.length <= 0 || arguments[0] === undefined ? { data: [] } : arguments[0];
// INNER JOIN
var innerJoin = function innerJoin(a, b, f) {
var m = a.length,
n = b.length,
c = [];
for (var i = 0; i < m; i++) {
var x = a[i];
for (var j = 0; j < n; j++) {
// cartesian product - all combinations
var y = void 0;
if (f) {
y = f([x, b[j]]) ? [x, b[j]] : undefined;
} else {
y = [x, b[j]];
}
if (y) c.push(y); // if a row is returned add it to the table
}
}
return c;
};
var where = function where(fns, data) {
// APPLY MULTIPLE WHERE CLASES WITH 'OR'
var whereOR = function whereOR(fns, data) {
var res = [];
fns.forEach(function (f) {
return res = res.concat(data.filter(f).reverse());
});
return res;
};
// APPLY MULTIPLE WHERE CLASES WITH 'OR'
var whereAND = function whereAND(fns, data) {
var res = [];
fns.forEach(function (f) {
return res = data.filter(f);
});
status.whereLogic = 'OR';
return res;
};
return status.whereLogic === 'AND' ? whereAND(fns, data) : whereOR(fns, data);
};
// GROUP DATASET BY ATTR
var groupBy = function groupBy(fns, data) {
// GROUP FUNCTION WHEN DATASET INST GROUPED
var group = function group(f, data) {
if (!data) return [];
var groupArray = function groupArray(f, data) {
var groupsMap = {};
var groups = [];
data.forEach(function (d) {
if (groupsMap[f(d)]) {
groupsMap[f(d)].push(d);
} else {
groupsMap[f(d)] = [d];
}
});
Object.keys(groupsMap).forEach(function (groupName) {
var items = groupsMap[groupName];
if (!Number.isNaN(Number.parseInt(groupName))) groupName = Number.parseInt(groupName);
groups.push([groupName, items]);
});
return groups;
};
if (_typeof(data[0][0]) != 'object' && _typeof(data[0][1]) === 'object') {
return regroup(f, data);
} else {
return groupArray(f, data);
}
};
// GROUP FUNCTION WHEN DATASET IS ALREADY GROUPED
var regroup = function regroup(f, data) {
for (var i = 0; i < data.length; i++) {
var g = data[i];
data[i][1] = group(f, g[1]);
}
return data;
};
fns.forEach(function (f) {
return data = group(f, data);
});
return data;
};
return {
select: function select(f) {
if (status.hasOwnProperty('select')) throw new Error('Duplicate SELECT');
status.select = f;
return query(status);
},
from: function from() {
for (var _len = arguments.length, data = Array(_len), _key = 0; _key < _len; _key++) {
data[_key] = arguments[_key];
}
if (status.hasOwnProperty('from')) throw new Error('Duplicate FROM');
status.from = data;
status.data = data;
return query(status);
},
where: function where() {
for (var _len2 = arguments.length, f = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
f[_key2] = arguments[_key2];
}
status.where = status.where ? status.where.concat(f) : f;
return query(status);
},
groupBy: function groupBy() {
for (var _len3 = arguments.length, f = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
f[_key3] = arguments[_key3];
}
if (status.hasOwnProperty('groupBy')) throw new Error('Duplicate GROUPBY');
status.groupBy = f;
return query(status);
},
orderBy: function orderBy(f) {
if (status.hasOwnProperty('orderBy')) throw new Error('Duplicate ORDERBY');
status.orderBy = f;
return query(status);
},
having: function having(f) {
status.having = f;
return query(status);
},
execute: function execute() {
if (status.data.length === 2) {
status.data = status.where ? innerJoin(status.data[0], status.data[1], status.where[0]) : innerJoin(status.data[0], status.data[1]);
status.whereLogic = 'AND';
} else {
status.data = status.data[0] || [];
}
if (status.where) status.data = where(status.where, status.data);
if (status.groupBy) status.data = groupBy(status.groupBy, status.data);
if (status.having) status.data = status.data.filter(status.having);
if (status.select) status.data = status.data.map(status.select);
if (status.orderBy) status.data = status.data.sort(status.orderBy);
return status.data;
}
};
};
exports.default = query;
\ No newline at end of file
(function(exports){
var methodCalls = {},
html = [],
consoleLog = console.log,
describing = false,
correct = 0,
incorrect = 0,
failed = [],
beforeCallbacks = [],
afterCallbacks = [];
var _expect = function(passed, msg, options){
options = options || {}
if(passed){
var successMsg = "Test Passed"
if (options.successMsg){
successMsg += ": " + options.successMsg
}
write(logFilter('<div class="console-passed">') + successMsg +
logFilter('</div>', true), true)
correct++
} else {
msg = _message(msg) || 'Invalid'
// extra credit feature - TODO: complete
if (options.extraCredit) {
msg = (options.extraCredit !== true) ? _message(options.extraCredit) : null
msg = combineMessages(["Test Missed", msg], ": ");
write(logFilter("<div class='console-missed'>") + msg +
logFilter("</div>", true), true)
incorrect++
}
else{
write(logFilter("<div class='console-failed'>Test Failed: ") + msg +
logFilter("</div>", true), true)
var error = new Test.Error(msg);
if (describing){
failed.push(error);
}
else{
throw error;
}
}
}
}
function logFilter( msg, lf ){
// detect node.js
if ( this.exports ){
return msg;
} else {
var m = msg.replace( /<[^>].*>/g, '');
// Add a LF only for empty messages that don't have the *lf* set
return ( m.length == 0 && ( ! lf ) ) ? "" : m + "\n";
}
}
function write(msg, noLineBreak){
if ((msg.length == 0) && (! this.exports)){
return
}
if (html.length == 0){
console.log(msg);
}
else{
html.push(msg);
if(!noLineBreak){
html.push(logFilter('<br>'));
}
}
}
function combineMessages(msgs, separator){
return msgs.filter(function(m){return m != null;}).join(separator)
}
function _message(msg, prefix){
if (typeof msg == 'function'){
msg = msg()
}else if (typeof msg == 'array'){
msg = combineMessages(msg, ' - ')
}
return prefix ? (prefix + ' - ' + msg) : msg
}
function logCall(name, useConsole){
methodCalls[name] = Test.callCount(name) + 1
if (useConsole){
console.log(name + " called");
}
}
var Test = {
callCount: function(name) {
return methodCalls[name] || 0
},
inspect: function(obj){
logCall('inspect')
if(typeof obj == 'string'){
return obj;
} else {
return obj && obj !== true ? JSON.stringify(obj) : ('' + obj)
}
},
describe: function(msg, fn) {
try{
if (describing) throw "cannot call describe within another describe"
logCall('describe')
describing = true
html.push(logFilter('<div class="console-describe"><h6>'));
html.push(_message(msg))
html.push(logFilter(':</h6>'));
// intercept console.log messages
console.log = write
fn();
}
finally{
html.push(logFilter('</div>'));
// restore log
console.log = consoleLog
console.log(html.join(''));
html = []
describing = false
beforeCallbacks = [];
afterCallbacks = [];
if (failed.length > 0){
throw failed[0];
}
}
},
it: function(msg, fn) {
try{
logCall('it');
html.push(logFilter('<div class="console-it"><h6>'))
html.push(_message(msg));
html.push(logFilter(':</h6>'));
beforeCallbacks.forEach(function(cb){
cb()
});
try{
fn();
} finally {
afterCallbacks.forEach(function(cb){
cb()
});
}
}
finally{