Skip to content

Commit 77ad0d3

Browse files
committed
Add and modify existing examples
I took many of these examples from the gh-pages branch. These examples are useful even outside of a Github Pages context, so I wanted to include them here. This makes it easier for the README to reference them. Since they are now in the main branch, I have taken care to point to CDN libraries where I could so that it doesn't get cluttered with vendor code, like for the codemirror library.
1 parent d86aca6 commit 77ad0d3

File tree

9 files changed

+488
-0
lines changed

9 files changed

+488
-0
lines changed

examples/GUI/demo.css

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
html {
2+
background:#222;
3+
margin:auto;
4+
width:80%;
5+
}
6+
7+
body{
8+
background: linear-gradient(#aaa 0, #ddd 10px, #fff 55px);
9+
border: 1px solid black;
10+
padding: 10px 20px;
11+
box-shadow: 5px 0px 30px #000;
12+
border-radius: 8px;
13+
}
14+
15+
h1 {
16+
text-align: center;
17+
color: #222;
18+
margin: 0 0 30px;
19+
}
20+
21+
.button {
22+
color: #333;
23+
background: linear-gradient(#eee, #ddd);
24+
border: 1px solid #222;
25+
border-radius: 3px;
26+
padding: 7px;
27+
margin-right: 5px;
28+
transition: .3s;
29+
font-family: ubuntu, sans-serif;
30+
font-size: 1em;
31+
}
32+
33+
.button:active {
34+
background: linear-gradient(#ddd, #eee);
35+
}
36+
37+
.button:hover, button:focus {
38+
box-shadow: 0 0 2px #222;
39+
}
40+
41+
#execute {
42+
margin-top: 5px;;
43+
width: 10%;
44+
min-width:100px;
45+
}
46+
47+
.CodeMirror {
48+
border: 1px solid #222;
49+
height: auto;
50+
}
51+
.CodeMirror-scroll {
52+
overflow-y: hidden;
53+
overflow-x: auto;
54+
}
55+
56+
.error {
57+
color:red;
58+
transition:.5s;
59+
overflow:hidden;
60+
}
61+
62+
#output {
63+
overflow: auto;
64+
}
65+
66+
table {
67+
width:auto;
68+
margin:auto;
69+
border:1px solid black;
70+
border-collapse:collapse;
71+
margin-bottom:10px;
72+
}
73+
74+
th, td {
75+
border:1px solid #777;
76+
}
77+
78+
footer {
79+
font-size:.8em;
80+
color: #222;
81+
}

examples/GUI/gui.js

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
var execBtn = document.getElementById("execute");
2+
var outputElm = document.getElementById('output');
3+
var errorElm = document.getElementById('error');
4+
var commandsElm = document.getElementById('commands');
5+
var dbFileElm = document.getElementById('dbfile');
6+
var savedbElm = document.getElementById('savedb');
7+
8+
// Start the worker in which sql.js will run
9+
var worker = new Worker("/dist/worker.sql-wasm.js");
10+
worker.onerror = error;
11+
12+
// Open a database
13+
worker.postMessage({action:'open'});
14+
15+
// Connect to the HTML element we 'print' to
16+
function print(text) {
17+
outputElm.innerHTML = text.replace(/\n/g, '<br>');
18+
}
19+
function error(e) {
20+
console.log(e);
21+
errorElm.style.height = '2em';
22+
errorElm.textContent = e.message;
23+
}
24+
25+
function noerror() {
26+
errorElm.style.height = '0';
27+
}
28+
29+
// Run a command in the database
30+
function execute(commands) {
31+
tic();
32+
worker.onmessage = function(event) {
33+
var results = event.data.results;
34+
toc("Executing SQL");
35+
36+
tic();
37+
outputElm.innerHTML = "";
38+
for (var i=0; i<results.length; i++) {
39+
outputElm.appendChild(tableCreate(results[i].columns, results[i].values));
40+
}
41+
toc("Displaying results");
42+
}
43+
worker.postMessage({action:'exec', sql:commands});
44+
outputElm.textContent = "Fetching results...";
45+
}
46+
47+
// Create an HTML table
48+
var tableCreate = function () {
49+
function valconcat(vals, tagName) {
50+
if (vals.length === 0) return '';
51+
var open = '<'+tagName+'>', close='</'+tagName+'>';
52+
return open + vals.join(close + open) + close;
53+
}
54+
return function (columns, values){
55+
var tbl = document.createElement('table');
56+
var html = '<thead>' + valconcat(columns, 'th') + '</thead>';
57+
var rows = values.map(function(v){ return valconcat(v, 'td'); });
58+
html += '<tbody>' + valconcat(rows, 'tr') + '</tbody>';
59+
tbl.innerHTML = html;
60+
return tbl;
61+
}
62+
}();
63+
64+
// Execute the commands when the button is clicked
65+
function execEditorContents () {
66+
noerror()
67+
execute (editor.getValue() + ';');
68+
}
69+
execBtn.addEventListener("click", execEditorContents, true);
70+
71+
// Performance measurement functions
72+
var tictime;
73+
if (!window.performance || !performance.now) {window.performance = {now:Date.now}}
74+
function tic () {tictime = performance.now()}
75+
function toc(msg) {
76+
var dt = performance.now()-tictime;
77+
console.log((msg||'toc') + ": " + dt + "ms");
78+
}
79+
80+
// Add syntax highlihjting to the textarea
81+
var editor = CodeMirror.fromTextArea(commandsElm, {
82+
mode: 'text/x-mysql',
83+
viewportMargin: Infinity,
84+
indentWithTabs: true,
85+
smartIndent: true,
86+
lineNumbers: true,
87+
matchBrackets : true,
88+
autofocus: true,
89+
extraKeys: {
90+
"Ctrl-Enter": execEditorContents,
91+
"Ctrl-S": savedb,
92+
}
93+
});
94+
95+
// Load a db from a file
96+
dbFileElm.onchange = function() {
97+
var f = dbFileElm.files[0];
98+
var r = new FileReader();
99+
r.onload = function() {
100+
worker.onmessage = function () {
101+
toc("Loading database from file");
102+
// Show the schema of the loaded database
103+
editor.setValue("SELECT `name`, `sql`\n FROM `sqlite_master`\n WHERE type='table';");
104+
execEditorContents();
105+
};
106+
tic();
107+
try {
108+
worker.postMessage({action:'open',buffer:r.result}, [r.result]);
109+
}
110+
catch(exception) {
111+
worker.postMessage({action:'open',buffer:r.result});
112+
}
113+
}
114+
r.readAsArrayBuffer(f);
115+
}
116+
117+
// Save the db to a file
118+
function savedb () {
119+
worker.onmessage = function(event) {
120+
toc("Exporting the database");
121+
var arraybuff = event.data.buffer;
122+
var blob = new Blob([arraybuff]);
123+
var a = document.createElement("a");
124+
a.href = window.URL.createObjectURL(blob);
125+
a.download = "sql.db";
126+
a.onclick = function() {
127+
setTimeout(function() {
128+
window.URL.revokeObjectURL(a.href);
129+
}, 1500);
130+
};
131+
a.click();
132+
};
133+
tic();
134+
worker.postMessage({action:'export'});
135+
}
136+
savedbElm.addEventListener("click", savedb, true);

examples/GUI/index.html

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf8">
5+
<title>sql.js demo: Online SQL interpreter</title>
6+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.css">
7+
<link rel="stylesheet" href="demo.css">
8+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/codemirror.js"></script>
9+
10+
</head>
11+
<body>
12+
<!-- Github ribbon -->
13+
<a href="https://github.com/kripken/sql.js"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://camo.githubusercontent.com/82b228a3648bf44fc1163ef44c62fcc60081495e/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f6c6566745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_left_red_aa0000.png"></a>
14+
15+
<h1>Online SQL interpreter</h1>
16+
17+
<main>
18+
<label for='commands'>Enter some SQL</label>
19+
<br>
20+
21+
<textarea id="commands">DROP TABLE IF EXISTS employees;
22+
CREATE TABLE employees( id integer, name text,
23+
designation text, manager integer,
24+
hired_on date, salary integer,
25+
commission float, dept integer);
26+
27+
INSERT INTO employees VALUES (1,'JOHNSON','ADMIN',6,'1990-12-17',18000,NULL,4);
28+
INSERT INTO employees VALUES (2,'HARDING','MANAGER',9,'1998-02-02',52000,300,3);
29+
INSERT INTO employees VALUES (3,'TAFT','SALES I',2,'1996-01-02',25000,500,3);
30+
INSERT INTO employees VALUES (4,'HOOVER','SALES I',2,'1990-04-02',27000,NULL,3);
31+
INSERT INTO employees VALUES (5,'LINCOLN','TECH',6,'1994-06-23',22500,1400,4);
32+
INSERT INTO employees VALUES (6,'GARFIELD','MANAGER',9,'1993-05-01',54000,NULL,4);
33+
INSERT INTO employees VALUES (7,'POLK','TECH',6,'1997-09-22',25000,NULL,4);
34+
INSERT INTO employees VALUES (8,'GRANT','ENGINEER',10,'1997-03-30',32000,NULL,2);
35+
INSERT INTO employees VALUES (9,'JACKSON','CEO',NULL,'1990-01-01',75000,NULL,4);
36+
INSERT INTO employees VALUES (10,'FILLMORE','MANAGER',9,'1994-08-09',56000,NULL,2);
37+
INSERT INTO employees VALUES (11,'ADAMS','ENGINEER',10,'1996-03-15',34000,NULL,2);
38+
INSERT INTO employees VALUES (12,'WASHINGTON','ADMIN',6,'1998-04-16',18000,NULL,4);
39+
INSERT INTO employees VALUES (13,'MONROE','ENGINEER',10,'2000-12-03',30000,NULL,2);
40+
INSERT INTO employees VALUES (14,'ROOSEVELT','CPA',9,'1995-10-12',35000,NULL,1);
41+
42+
SELECT designation,COUNT(*) AS nbr, (AVG(salary)) AS avg_salary FROM employees GROUP BY designation ORDER BY avg_salary DESC;
43+
SELECT name,hired_on FROM employees ORDER BY hired_on;</textarea>
44+
45+
<button id="execute" class="button">Execute</button>
46+
<button id='savedb' class="button">Save the db</button>
47+
<label class="button">Load an SQLite database file: <input type='file' id='dbfile' ></label>
48+
49+
<div id="error" class="error"></div>
50+
51+
<pre id="output">Results will be displayed here</pre>
52+
</main>
53+
54+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.46.0/mode/sql/sql.min.js"></script>
55+
56+
<footer>
57+
Original work by kripken (<a href='https://github.com/kripken/sql.js'>sql.js</a>).
58+
C to Javascript compiler by kripken (<a href='https://github.com/kripken/emscripten'>emscripten</a>).
59+
Project now maintained by <a href='https://github.com/lovasoa'>lovasoa</a>
60+
</footer>
61+
62+
<script type="text/javascript" src="gui.js"></script>
63+
</body>
64+
</html>

examples/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
To show these examples locally, first run:
3+
./start_local_server.py
4+
5+
Then, open http://localhost:8081/index.html in a local browser.
6+

examples/persistent.html

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf8">
5+
<title>Persistent sqlite</title>
6+
<script src="/dist/sql-wasm.js"></script>
7+
</head>
8+
<body>
9+
<p>You have seen this page <span id="views">0</span> times.</p>
10+
<div>
11+
You have been here on the following dates: <ol id="dates"></ol>
12+
</div>
13+
<script>
14+
15+
function toBinArray (str) {
16+
var l = str.length,
17+
arr = new Uint8Array(l);
18+
for (var i=0; i<l; i++) arr[i] = str.charCodeAt(i);
19+
return arr;
20+
}
21+
22+
function toBinString (arr) {
23+
var uarr = new Uint8Array(arr);
24+
var strings = [], chunksize = 0xffff;
25+
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
26+
for (var i=0; i*chunksize < uarr.length; i++){
27+
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
28+
}
29+
return strings.join('');
30+
}
31+
32+
// Normally Sql.js tries to load sql-wasm.wasm relative to the page, not relative to the javascript
33+
// doing the loading. So, we help it find the .wasm file with this function.
34+
var config = {
35+
locateFile: filename => `${baseUrl}/${filename}`
36+
}
37+
initSqlJs(config).then(function(SQL){
38+
var dbstr = window.localStorage.getItem("viewcount.sqlite");
39+
if (dbstr) {
40+
var db = new SQL.Database(toBinArray(dbstr));
41+
} else {
42+
var db = new SQL.Database();
43+
db.run("CREATE TABLE views (date INTEGER PRIMARY KEY)");
44+
}
45+
db.run("INSERT INTO views(date) VALUES (?)", [Date.now()]);
46+
47+
document.getElementById('views').textContent = db.exec("SELECT COUNT(*) FROM views")[0].values[0][0];
48+
49+
var count = 0,
50+
dates = document.getElementById("dates");
51+
52+
db.each("SELECT date FROM views ORDER BY date ASC",
53+
function callback (row) {
54+
var li = document.createElement("li");
55+
li.textContent = new Date(row.date);
56+
dates.appendChild(li);
57+
}, function done () {
58+
var dbstr = toBinString(db.export());
59+
window.localStorage.setItem("viewcount.sqlite", dbstr);
60+
}
61+
);
62+
});
63+
64+
</script>
65+
</body>
66+
</html>

0 commit comments

Comments
 (0)