Skip to content

Instantly share code, notes, and snippets.

@jmahmood
Created September 6, 2012 08:15
Show Gist options
  • Save jmahmood/3652904 to your computer and use it in GitHub Desktop.
Save jmahmood/3652904 to your computer and use it in GitHub Desktop.
Coffeescript WebSQL
# This is a simple websql class I built in coffeescript.
# This gives a good example of how to use "fat arrows" to maintain a different
# level's "this" pointer - without fat arrows, you will not be able to save @results
"use strict";
root = exports ? this
class @websql
constructor: ->
@DBNAME = "websql"
@DBVER = 1.0
@DBDESC = "This DB should not exist. It is a base class for real DBs"
@DBSIZE = 1048*1048*2
@TABLE="websql_table"
@LOAD_QUERY="SELECT * FROM #{@TABLE} WHERE ?"
@INSERT_QUERY="INSERT INTO #{@TABLE} (id, text) VALUES (?, ?)"
@db = root.openDatabase(@DBNAME, @DBVER, @DBDESC, @DBSIZE);
table: ->
@db.transaction (tx) =>
console.log "Creating DB"
tx.executeSql("CREATE TABLE IF NOT EXISTS #{@TABLE} (id unique, text)",
[],
(tx,results) => console.log(results),
(tx,error) => console.error(error),
)
insert: ->
@db.transaction (tx) =>
console.log "Creating Test Data"
tx.executeSql(@INSERT_QUERY,
[1,"test"],
(tx,results) => console.log(results),
(tx,error) => console.error(error),
)
# The most basic loads by id.
load: (id) ->
@db.transaction (tx) =>
console.log "Loading #{id}"
tx.executeSql(@LOAD_QUERY,
[id],
(tx,@results) => console.log(@results),
(tx,error) => console.error(error),
)
@results
@pharshal
Copy link

Hi,

Can the insert function be modified to return the id of the created row? i.e. how to return results.insertId to function which calls insert() ? I tried modifying the 'insert()' like the way it's returning in 'load(id)' but it returns 'undefined' .

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment