@@ -4,51 +4,83 @@ import initSqlJs from "sql.js";
44
55
66export default class App extends React . Component {
7+
78 constructor ( ) {
89 super ( ) ;
9- this . state = { db : null , err : null , result : null }
10+ this . state = { db : null , err : null , results : null }
1011 }
12+
1113 componentDidMount ( ) {
14+ // sql.js needs to fetch its wasm file, so we cannot immediately instantiate the database
15+ // without any configuration, initSqlJs will fetch the wasm files directly from the same path as the js
16+ // see ../config-overrides.js
1217 initSqlJs ( )
1318 . then ( SQL => this . setState ( { db : new SQL . Database ( ) } ) )
1419 . catch ( err => this . setState ( { err } ) ) ;
1520 }
21+
1622 exec ( sql ) {
17- let result = null , err = null ;
23+ let results = null , err = null ;
1824 try {
19- result = this . state . db . exec ( sql ) ;
25+ // The sql is executed synchronously on the UI thread.
26+ // You may want to use a web worker
27+ results = this . state . db . exec ( sql ) ; // an array of objects is returned
2028 } catch ( e ) {
29+ // exec throws an error when the SQL statement is invalid
2130 err = e
2231 }
23- this . setState ( { result , err } )
32+ this . setState ( { results , err } )
2433 }
34+
35+ /**
36+ * Renders a single value of the array returned by db.exec(...) as a table
37+ */
2538 renderResult ( { columns, values } ) {
39+ return (
40+ < table >
41+ < thead >
42+ < tr >
43+ { columns . map ( columnName =>
44+ < td > { columnName } </ td >
45+ ) }
46+ </ tr >
47+ </ thead >
2648
27- return < table >
28- < thead >
29- < tr >
30- { columns . map ( c => < td > { c } </ td > ) }
31- </ tr >
32- </ thead >
33- < tbody >
34- { values . map ( row =>
35- < tr > { row . map ( v => < td > { v } </ td > ) } </ tr >
36- ) }
37- </ tbody >
38- </ table >
49+ < tbody >
50+ { values . map ( row => // values is an array of arrays representing the results of the query
51+ < tr >
52+ { row . map ( value =>
53+ < td > { value } </ td >
54+ ) }
55+ </ tr >
56+ ) }
57+ </ tbody >
58+ </ table >
59+ ) ;
3960 }
61+
4062 render ( ) {
41- let { db, err, result } = this . state ;
63+ let { db, err, results } = this . state ;
4264 if ( ! db ) return < pre > Loading...</ pre > ;
4365 return (
4466 < div className = "App" >
67+
4568 < h1 > React SQL interpreter</ h1 >
69+
4670 < textarea
4771 onChange = { e => this . exec ( e . target . value ) }
48- placeholder = "Enter some SQL. No inpiration ? Try “select sqlite_version()”" > </ textarea >
72+ placeholder = "Enter some SQL. No inpiration ? Try “select sqlite_version()”"
73+ > </ textarea >
74+
4975 < pre className = "error" > { ( err || "" ) . toString ( ) } </ pre >
50- < pre > { result ? result . map ( this . renderResult ) : "" } </ pre >
76+
77+ < pre > { results
78+ ? results . map ( this . renderResult ) // results contains one object per select statement in the query
79+ : ""
80+ } </ pre >
81+
5182 </ div >
5283 ) ;
5384 }
85+
5486}
0 commit comments