Created
April 2, 2010 15:19
-
-
Save mrjjwright/353245 to your computer and use it in GitHub Desktop.
From NoSQLite, nice example of the power of flow.js for doing something like saving one or multiple objects to the db
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
save: (table, obj, tx_flag, callback) -> | |
#augment object with guid unless options say not to | |
if @options.no_guid is false | |
if not _.isArray(obj) | |
obj.guid: Math.uuidFast() | |
else for o in obj | |
o.guid: Math.uuidFast() | |
inserts: [] | |
inserts: sql.insert(table, table_obj, @options.core_data_mode) for table_obj in obj if _.isArray(obj) | |
inserts.push(sql.insert(table, obj, @options.core_data_mode)) if not _.isArray(obj) | |
the_obj: if _.isArray(obj) then obj[0] else obj | |
self: this | |
db: @db | |
flow.exec( | |
-> | |
# start a transaction if we aren't in one | |
if not tx_flag | |
db.query "begin transaction", this | |
else | |
this() | |
-> | |
# save the first one | |
self_this: this | |
try_first_one: -> | |
db.query inserts[0].escaped, null, (err) -> | |
if err? | |
# This is NoSQLite, let's see if we can fix this! | |
compensating_sql: self.compensating_sql(table, the_obj, err) | |
if compensating_sql? | |
db.query compensating_sql, null, (err) -> | |
if err? then callback(err) if callback? | |
else try_first_one() | |
else | |
callback(err) if callback? | |
else | |
self_this() | |
try_first_one() | |
-> | |
# save the rest | |
self_this: this | |
do_insert: (i) -> | |
db.query inserts[i].escaped, (err) -> | |
if err? | |
callback(err) | |
return | |
if i-- then do_insert(i) | |
else self_this() | |
if inserts.length > 1 then do_insert(inserts.length-1) | |
else this() | |
-> | |
# commit the transaction | |
if not tx_flag | |
db.query "commit", this | |
else | |
this() | |
-> | |
# callback to the user | |
callback(null, "success") if callback? | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment