[OpenLayers-Commits] r11434 - in sandbox/jgrocha/openlayers: examples lib lib/OpenLayers/Protocol/SQL

commits-20090109 at openlayers.org commits-20090109 at openlayers.org
Thu Feb 24 11:43:16 EST 2011


Author: jgrocha
Date: 2011-02-24 08:43:16 -0800 (Thu, 24 Feb 2011)
New Revision: 11434

Added:
   sandbox/jgrocha/openlayers/examples/websql.html
   sandbox/jgrocha/openlayers/examples/websql.js
   sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/WebSQL.js
Modified:
   sandbox/jgrocha/openlayers/examples/protocol-localsql.html
   sandbox/jgrocha/openlayers/lib/OpenLayers.js
   sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/LocalSQL.js
Log:
improved WebSQL protocol example

Modified: sandbox/jgrocha/openlayers/examples/protocol-localsql.html
===================================================================
--- sandbox/jgrocha/openlayers/examples/protocol-localsql.html	2011-02-24 16:35:45 UTC (rev 11433)
+++ sandbox/jgrocha/openlayers/examples/protocol-localsql.html	2011-02-24 16:43:16 UTC (rev 11434)
@@ -1,5 +1,8 @@
 <html xmlns="http://www.w3.org/1999/xhtml">
-	<head><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /><meta name="apple-mobile-web-app-capable" content="yes" />
+	<head>
+		<!--
+		<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /><meta name="apple-mobile-web-app-capable" content="yes" />
+		-->
 		<link rel="stylesheet" href="../theme/default/style.css" type="text/css" />
 		<link rel="stylesheet" href="style.css" type="text/css" />
 		<style type="text/css">
@@ -16,10 +19,10 @@
 	var map, vector, protocol, modify;
 
 	function init() {
-		// create Gears protocol
+		// create LocalSQL protocol
 		protocol = new OpenLayers.Protocol.SQL.LocalSQL({
-			databaseName: "db_name",
-			tableName: "table_name",
+			databaseName: "lausanne",
+			tableName: "restaurant",
 			saveFeatureState: false
 		});
 
@@ -140,22 +143,33 @@
 		return list;
 	}
 
+	function myfunction(response) {
+		console.log('Viva o Jorge');
+		console.debug(response);
+		// alert('Thank you for calling me!');
+		/*
+ 		if (response.features) {
+ 		vector.addFeatures(response.features);
+ 		}
+ 		*/
+	}
+
 	function _sync() {
-		if (!LocalSQLIsSupported()) {
-			return;
-		}
-		var resp = protocol.read();
-		if (!resp.success()) {
-			OpenLayers.Console.error("reading from Gears DB failed");
-			return;
-		}
-		vector.destroyFeatures();
-		if (!resp.features || resp.features.length <= 0) {
-			displayResult("No features to read");
-			return;
-		}
-		vector.addFeatures(resp.features);
-		displayResult("features successfully read");
+            if (!LocalSQLIsSupported()) {
+                return;
+            }
+            var resp = protocol.read();
+            if (!resp.success()) {
+                OpenLayers.Console.error("reading from Gears DB failed");
+                return;
+            }
+            vector.destroyFeatures();
+            if (!resp.features || resp.features.length <= 0) {
+                displayResult("No features to read");
+                return;
+            }
+            vector.addFeatures(resp.features);
+            displayResult("features successfully read");
 	}
 
 	function _commit() {

Added: sandbox/jgrocha/openlayers/examples/websql.html
===================================================================
--- sandbox/jgrocha/openlayers/examples/websql.html	                        (rev 0)
+++ sandbox/jgrocha/openlayers/examples/websql.html	2011-02-24 16:43:16 UTC (rev 11434)
@@ -0,0 +1,91 @@
+<!DOCTYPE html>
+<html>
+	<head><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /><meta name="apple-mobile-web-app-capable" content="yes" />
+		<title>OpenLayers Polygon Hole Digitizing</title>
+		<link rel="stylesheet" href="../theme/default/style.css" type="text/css">
+		<link rel="stylesheet" href="style.css" type="text/css">
+		<style>
+	.olControlAttribution {
+		bottom: 5px;
+		font-size: 9px;
+	}
+		</style>
+	</head>
+	<body>
+		<h1 id="title">Local Storage with Web SQL</h1>
+		<div id="tags">
+			offline storage sql protocol
+		</div>
+		<p id="shortdesc">
+			The WebSQL protocol can be used to work with local vector feature storage.
+		</p>
+		<div id="map" class="smallmap">
+		</div>
+		<ul id="controlToggle">
+			<li>
+				<input type="radio" name="type" value="none" id="noneToggle"
+				onclick="toggleControl(this);" checked="checked" />
+				<label for="noneToggle">
+					navigate
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="point" id="pointToggle"
+				onclick="toggleControl(this);" />
+				<label for="pointToggle">
+					draw point
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="line" id="lineToggle"
+				onclick="toggleControl(this);" />
+				<label for="lineToggle">
+					draw line
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="polygon" id="polygonToggle"
+				onclick="toggleControl(this);" />
+				<label for="polygonToggle">
+					draw polygon
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="modify" id="modifyToggle"
+				onclick="toggleControl(this);" />
+				<label for="modifyToggle">
+					Modify features
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="remove" id="removeToggle"
+				onclick="toggleControl(this);" />
+				<label for="removeToggle">
+					Remove features
+				</label>
+			</li>
+			<li>
+				<input type="radio" name="type" value="removefromwebsql" id="removefromwebsqlToggle"
+				onclick="toggleControl(this);" />
+				<label for="removefromwebsqlToggle">
+					Remove features using state change and stratergy.save()
+				</label>
+			</li>
+		</ul>
+		<p>
+			Use the shift key to select multiple features.  Use the ctrl key to
+			toggle selection on features one at a time.  Note: the "clickout" option has no
+			effect when "hover" is selected.
+		</p>
+		<div id="docs">
+			<p>
+				See the
+				<a href="websql.js" target="_blank">websql.js source</a> for details on how this is done.
+			</p>
+		</div>
+		<script src="../lib/OpenLayers.js">
+		</script>
+		<script src="websql.js">
+		</script>
+	</body>
+</html>

Added: sandbox/jgrocha/openlayers/examples/websql.js
===================================================================
--- sandbox/jgrocha/openlayers/examples/websql.js	                        (rev 0)
+++ sandbox/jgrocha/openlayers/examples/websql.js	2011-02-24 16:43:16 UTC (rev 11434)
@@ -0,0 +1,70 @@
+var saveStrategy = new OpenLayers.Strategy.Save({auto: true});
+
+var vectors = new OpenLayers.Layer.Vector("Local Storage", {
+	strategies: [ new OpenLayers.Strategy.Fixed(), saveStrategy	],
+	eventListeners: {
+		featuremodified: function(obj) {
+			console.log('featuremodified');
+		},
+		beforefeatureremoved: function(obj) {
+			console.log('beforefeatureremoved');
+		},
+		featureremoved: function(obj) {
+			console.log('featureremoved');
+		}
+	},
+	protocol: new OpenLayers.Protocol.WebSQL({databaseName: 'poi', tableName: 'restaurants', initialSize: 8*1024*1024})
+});
+
+function toggleControl(element) {
+	for(key in drawControls) {
+		var control = drawControls[key];
+		if(element.value == key && element.checked) {
+			control.activate();
+		} else {
+			control.deactivate();
+		}
+	}
+}
+
+drawControls = {
+	point: new OpenLayers.Control.DrawFeature(
+	vectors, OpenLayers.Handler.Point
+	),
+	line: new OpenLayers.Control.DrawFeature(
+	vectors, OpenLayers.Handler.Path
+	),
+	polygon: new OpenLayers.Control.DrawFeature(
+	vectors, OpenLayers.Handler.Polygon
+	),
+	modify: new OpenLayers.Control.ModifyFeature(vectors),
+	remove: new OpenLayers.Control.SelectFeature(
+	vectors, { onSelect: function(feature) {
+			console.log('feature has been destroyed');
+			vectors.destroyFeatures([feature]);
+		}
+	}),
+	removefromwebsql: new OpenLayers.Control.SelectFeature(
+	vectors, { onSelect: function(feature) {
+			console.log('feature state changed to DELETE, and then strategy.save()');
+			if (feature) {
+				feature.state = OpenLayers.State.DELETE;
+				saveStrategy.save();
+			}
+		}
+	})
+};
+
+var map = new OpenLayers.Map({
+	div: "map",
+	layers: [
+	new OpenLayers.Layer.OSM(),
+	vectors
+	],
+	center: new OpenLayers.LonLat(0,0),
+	zoom: 1
+});
+
+for(var key in drawControls) {
+	map.addControl(drawControls[key]);
+}

Modified: sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/LocalSQL.js
===================================================================
--- sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/LocalSQL.js	2011-02-24 16:35:45 UTC (rev 11433)
+++ sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/LocalSQL.js	2011-02-24 16:43:16 UTC (rev 11434)
@@ -100,15 +100,21 @@
  	* tested, jgr
  	*/
 	initializeDatabase: function() {
+		console.log('The database ' + this.databaseName + ' is about to be created with the table ' + this.tableName);
 		this.db = window.openDatabase('Open Layers', '1.0', this.databaseName, 8*1024);
-		this.db.transaction( function(tx) {
+		var onFailure = function (x) {
+			console.log('something went wrong');
+			console.debug(x);
+		}
+		var onSuccess = function(tx) {
 			tx.executeSql("create table if not exists " + this.tableName +
 			" (fid TEXT UNIQUE, geometry TEXT, properties TEXT, state TEXT)",
 			[], function() {
-				console.log("success create table if not exist");
+				// console.log("success create table if not exist");
 			}
 			);
-		});
+		}
+		this.db.transaction( OpenLayers.Function.bind(onSuccess, this), onFailure);
 	},
 	/**
  	* APIMethod: destroy
@@ -156,37 +162,57 @@
  	* check the possible options that can be passed
  	*/
 	read: function(options) {
+		// console.debug(options);
 		OpenLayers.Protocol.prototype.read.apply(this, arguments);
 		options = OpenLayers.Util.applyDefaults(options, this.options);
 
 		var feature, features = [];
-		var features = [];
-		this.db.transaction( function(tx) {
+		var resp;
+		var after = this.afterread;
+		var onFailure = function (x) {
+			console.log('something went wrong');
+			console.debug(x);
+		}
+		var onSuccess = function(tx) {
+			this
+			jgr
 			tx.executeSql("select * from " + this.tableName, [], function(tx, results) {
 				for (i = 0; i < results.rows.length; i++) {
-					feature = this.unfreezeFeature(results.rows.item(i));
-					if (this.evaluateFilter(feature, options.filter)) {
-						if (!options.noFeatureStateReset) {
-							feature.state = null;
-						}
-						features.push(feature);
-					}
+					feature = results.rows.item(i);
+					features.push(feature);
 				}
-			}, function() {
+				resp = new OpenLayers.Protocol.Response({
+					code: OpenLayers.Protocol.Response.SUCCESS,
+					requestType: "read",
+					features: features
+				});
+				// this.afterread(resp);
 			});
-		});
-		var resp = new OpenLayers.Protocol.Response({
-			code: OpenLayers.Protocol.Response.SUCCESS,
-			requestType: "read",
-			features: features
-		});
-
-		if (options && options.callback) {
-			options.callback.call(options.scope, resp);
 		}
-
+		this.db.transaction( OpenLayers.Function.bind(onSuccess, this), onFailure);
+		console.log('resp returned...');
+		// console.debug(resp);
+		// console.debug(resp.features);
+		// console.debug(resp.features.length);
 		return resp;
 	},
+	afterread: function(resp) {
+		console.log('afterread was called');
+		console.debug(resp);
+		var feature, features = [];
+		var wkt;
+		for (i = 0, len = resp.features.length; i < len; i++) {
+			row = resp.features[i];
+			wkt = row.geometry;
+			if (wkt == this.NULL_GEOMETRY) {
+				feature = new OpenLayers.Feature.Vector();
+			} else {
+				feature = this.wktParser.read(wkt);
+			}
+			// feature = this.unfreezeFeature(resp.features[i]);
+			features.push(feature);
+		}
+	},
 	/**
  	* Method: unfreezeFeature
  	*
@@ -197,20 +223,26 @@
  	* {<OpenLayers.Feature.Vector>}
  	*/
 	unfreezeFeature: function(row) {
+		console.debug(row);
+
 		var feature;
-		var wkt = row.fieldByName('geometry');
+		var wkt = row.geometry;
+		// var wkt = row.fieldByName('geometry');
+
 		if (wkt == this.NULL_GEOMETRY) {
 			feature = new OpenLayers.Feature.Vector();
 		} else {
 			feature = this.wktParser.read(wkt);
 		}
 
-		feature.attributes = this.jsonParser.read(
-		row.fieldByName('properties'));
+		// feature.attributes = this.jsonParser.read( row.fieldByName('properties'));
+		feature.attributes = this.jsonParser.read( row.properties);
 
-		feature.fid = this.extractFidFromField(row.fieldByName('fid'));
+		// feature.fid = this.extractFidFromField(row.fieldByName('fid'));
+		feature.fid = this.extractFidFromField(row.fid);
 
-		var state = row.fieldByName('state');
+		// var state = row.fieldByName('state');
+		var state = row.state;
 		if (state == this.NULL_FEATURE_STATE) {
 			state = null;
 		}
@@ -313,12 +345,14 @@
 
 			var params = this.freezeFeature(feature);
 
-			this.db.transaction( function(tx) {
-			tx.executeSql("REPLACE INTO " + this.tableName + " (fid, geometry, properties, state) VALUES (?, ?, ?, ?)",
-			params,
-			function() {},
-			function() {});
-			};
+			var onFailure = function (x) {
+				console.log('something went wrong');
+				console.debug(x);
+			}
+			var onSuccess = function(tx) {
+				tx.executeSql('REPLACE INTO ' + this.tableName + ' (fid, geometry, properties, state) VALUES (?, ?, ?, ?)', params);
+			}
+			this.db.transaction( OpenLayers.Function.bind(onSuccess, this), onFailure);
 
 			var clone = feature.clone();
 			clone.fid = this.extractFidFromField(params[0]);

Added: sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/WebSQL.js
===================================================================
--- sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/WebSQL.js	                        (rev 0)
+++ sandbox/jgrocha/openlayers/lib/OpenLayers/Protocol/SQL/WebSQL.js	2011-02-24 16:43:16 UTC (rev 11434)
@@ -0,0 +1,453 @@
+/**
+ * @requires OpenLayers/Protocol/SQL.js
+ * @requires OpenLayers/Format/GeoJSON.js
+ */
+
+OpenLayers.Protocol.WebSQL = OpenLayers.Class(OpenLayers.Protocol.SQL, {
+    
+    /**
+     * Property: maxId
+     * {Integer} Used internally to keep track of max feature id.
+     */
+    maxId: 0,
+    
+    /**
+     * APIProperty: databaseVersion
+     * {String} Optional database verion number.  Default is "".
+     */
+    databaseVersion: "",
+    
+    /**
+     * APIProperty: databaseName
+     * {String} Database name.  Default is "ol".
+     */
+    databaseName: "ol",
+    
+    /**
+     * APIProperty: databaseTitle
+     * {String} Display name for the database.  Default is 
+     *     "OpenLayers.Protocol.WebSQL".
+     */
+    databaseDescription: "OpenLayers.Protocol.WebSQL",
+    
+    /**
+     * APIProperty: tableName
+     * {String} Database name.  A table name is automatically generated if one
+     *     is not provided in the protocol configuration.
+     */
+    tableName: null,
+    
+    /**
+     * Property: db
+     * {Database}
+     */
+    db: null,
+
+    /**
+     * Property: initialSize
+     * {Database}
+     */
+    initialSize: 5*1024*1024,
+
+    /**
+     * APIProperty: supported
+     * {Boolean} The environment supports this protocol.
+     */
+    supported: (typeof window.openDatabase === "function"),
+
+    /**
+     * Constructor: OpenLayers.Protocol.WebSQL
+     * Create a new protocol for reading and writing feature data using the
+     *     Web SQL protocol (http://www.w3.org/TR/webdatabase/).
+     *
+     * Parameters:
+     * options - {Object} Optional properties to be set on the protocol.
+     */
+    initialize: function(options) {
+        if (this.supported) {
+            OpenLayers.Protocol.prototype.initialize.apply(this, [options]);
+            if (!this.format) {
+                this.format = new OpenLayers.Format.GeoJSON();
+            }
+            if (!this.tableName) {
+                this.tableName = OpenLayers.Util.createUniqueID("websql_")
+            }
+            this.initializeDatabase();
+        }
+    },
+    
+    /**
+     * Method: destroy
+     * Clean up.
+     */
+    destroy: function() {
+        if (!this.options || !this.options.format) {
+            this.format.destroy();
+        }
+        this.format = null;
+        OpenLayers.Protocol.SQL.prototype.destroy.apply(this, arguments);
+    },
+    
+    /**
+     * Method: initializeDatabase
+     */
+    initializeDatabase: function() {
+        this.db = openDatabase(this.databaseName, this.databaseVersion, this.databaseDescription, this.initialSize);
+        this.transaction(function(tx) {
+            this.executeSql(
+                tx,
+                "CREATE TABLE IF NOT EXISTS " + this.tableName +
+                    " (id INTEGER PRIMARY KEY, feature TEXT)",
+                [],
+                this.executeSql(
+                    tx,
+                    "SELECT MAX(id) as count FROM " + this.tableName,
+                    [],
+                    function(tx, result) {
+                        this.maxId = result.rows.item(0).count || 0;
+                    }
+                )
+            )
+        });
+    },
+    
+    /**
+     * Method: transaction
+     * Triggers a transaction on the database.
+     *
+     * Parameters:
+     * execute - {Function} The sql transaction callback to execute.
+     * failure - {Function} The error callback.
+     * success - {Function} The success callback.
+     */
+    transaction: function(execute, failure, success) {
+        if (this.supported) {
+            this.db.transaction(
+                OpenLayers.Function.bind(execute, this),
+                OpenLayers.Function.bind(failure || OpenLayers.Function.Void, this),
+                OpenLayers.Function.bind(success || OpenLayers.Function.Void, this)
+            );
+        } else {
+            if (failure) {
+                failure.apply(this, ["Protocol not supported"]);
+            }
+        }
+    },
+    
+    /**
+     * Method: executeSql
+     * Call transaction.executeSql with callbacks bound to this protocol.
+     *
+     * Parameters:
+     * transaction - {Transaction}
+     * sql - {String} The SQL to execute
+     * args - {Array} A list of arguments for ? replacement in the sql
+     * callback - {Function} The statement callback.
+     * failure - {Function} The statement error callback.
+     */
+    executeSql: function(transaction, sql, args, callback, failure) {
+        transaction.executeSql(
+            sql, args,
+            OpenLayers.Function.bind(callback || OpenLayers.Function.Void, this),
+            OpenLayers.Function.bind(failure || OpenLayers.Function.Void, this)
+        );
+    },
+
+    /**
+     * Method: read
+     * Read all features from the database and return a
+     *     <OpenLayers.Protocol.Response> instance. If the options parameter
+     *     contains a callback attribute, the function is called with the response
+     *     as a parameter.
+     *
+     * Parameters:
+     * options - {Object} Optional object for configuring the request.
+     *
+     * Returns:
+     * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
+     *      object.
+     */
+    read: function(options) {
+        options = OpenLayers.Util.applyDefaults(options, this.options || {});
+        var response = new OpenLayers.Protocol.Response({requestType: "read"});
+        this.transaction(function(tx) {
+            this.executeSql(tx, "SELECT * from " + this.tableName, [],
+                function(tx, result) {
+                    response.priv = {transaction: tx, result: result};
+                    this.handleResponse(response, options);
+                },
+                function(tx, error) {
+                    response.priv = {transaction: tx, error: error};
+                    this.handleResponse(response, options);
+                }
+            );
+        });
+    },
+    
+    /**
+     * Method: create
+     * Construct a request for writing newly created features.
+     *
+     * Parameters:
+     * features - {Array({<OpenLayers.Feature.Vector>})} or
+     *     {<OpenLayers.Feature.Vector>}
+     * options - {Object} Optional object for configuring the request.
+     *
+     * Returns:
+     * {<OpenLayers.Protocol.Response>} A response object, whose "priv"
+     *     property references the transaction, this object is also passed to
+     *     the callback function when the request completes.
+     */
+    create: function(feature, options) {
+        options = OpenLayers.Util.applyDefaults(options, this.options || {});
+        var response = new OpenLayers.Protocol.Response({
+            reqFeatures: [feature], requestType: "create"
+        });
+        this.transaction(function(tx) {
+            this.executeSql(
+                tx,
+                "INSERT INTO " + this.tableName + " (id, feature) VALUES (?, ?)",
+                [this.maxId + 1, this.format.write(feature)],
+                function(tx, result) { 
+                    response.priv = {transaction: tx, result: result};
+                    this.handleResponse(response, options);
+                },
+                function(tx, error) {
+                    response.priv = {transaction: tx, error: error};
+                    this.handleResponse(response, options);
+                }
+            );
+        });
+    },
+
+    /**
+     * Method: update
+     * Construct a request updating modified feature.
+     *
+     * Parameters:
+     * feature - {<OpenLayers.Feature.Vector>}
+     * options - {Object} Optional object for configuring the request.
+     *     This object is modified and should not be reused.
+     *
+     * Returns:
+     * {<OpenLayers.Protocol.Response>} A response object, whose "priv"
+     *     property references the transaction, this object is also passed to
+     *     the callback function when the request completes, its "features"
+     *     property is then populated with the the feature received from the
+     *     database.
+     */
+    update: function(feature, options) {
+        options = OpenLayers.Util.applyDefaults(options, this.options || {});
+        var response = new OpenLayers.Protocol.Response({
+            reqFeatures: [feature], requestType: "update"
+        });
+        this.transaction(function(tx) {
+            this.executeSql(
+                tx,
+                "REPLACE INTO "+ this.tableName + " (id, feature) VALUES (?, ?)",
+                [feature.fid, this.format.write(feature)],
+                function(tx, result) { 
+                    response.priv = {transaction: tx, result: result};
+                    this.handleResponse(response, options);
+                },
+                function(tx, error) {
+                    response.priv = {transaction: tx, error: error};
+                    this.handleResponse(response, options);
+                }
+            );
+        });
+    },
+
+    /**
+     * Method: delete
+     * Construct a request deleting a removed feature.
+     *
+     * Parameters:
+     * feature - {<OpenLayers.Feature.Vector>}
+     * options - {Object} Optional object for configuring the request.
+     *
+     * Returns:
+     * {<OpenLayers.Protocol.Response>} A response object, whose "priv"
+     *     property references the transaction, this object is also passed to
+     *     the callback function when the request completes.
+     */
+    "delete": function(feature, options) {
+        options = OpenLayers.Util.applyDefaults(options, this.options || {});
+        var response = new OpenLayers.Protocol.Response({
+            reqFeatures: [feature], requestType: "delete"
+        });
+        this.transaction(function(tx) {
+            this.executeSql(tx, "DELETE FROM " + this.tableName + " where id=?",
+                [feature.fid],
+                function(tx, result) { 
+                    response.priv = {transaction: tx, result: result};
+                    this.handleResponse(response, options);
+                },
+                function(tx, error) {
+                    response.priv = {transaction: tx, error: error};
+                    this.handleResponse(response, options);
+                }
+            );
+        });
+    },
+    
+    /**
+     * Method: handleResponse
+     * Deals with responses and calls any specified callback.
+     *
+     * Parameters:
+     * response - {OpenLayers.Protocol.Response} The response.
+     * options - {Object}
+     */
+    handleResponse: function(response, options) {
+        var result = response.priv.result;
+        if (result) {
+            switch (response.requestType) {
+                case "create":
+                    this.maxId = result.insertId;
+                    break;
+                case "read":
+                    var row, feature;
+                    var len = result.rows.length;
+                    response.features = new Array(len);
+                    for(var i=0; i<len; ++i) {
+                        row = result.rows.item(i);
+                        feature = this.format.read(row["feature"], "Feature");
+                        feature.fid = row["id"];
+                        response.features[i] = feature;
+                    }
+                    break;
+            }
+            response.code = OpenLayers.Protocol.Response.SUCCESS;
+        } else {
+            response.code = OpenLayers.Protocol.Response.FAILURE;
+        }
+        if (options.callback) {
+            options.callback.call(options.scope, response);
+        }
+    },
+    
+    /**
+     * Method: commit
+     * Iterate over each feature and take action based on the feature state.
+     *     Possible actions are create, update and delete.
+     *
+     * Parameters:
+     * features - {Array({<OpenLayers.Feature.Vector>})}
+     * options - {Object} Optional object for setting up intermediate commit
+     *     callbacks.
+     *
+     * Valid options:
+     * create - {Object} Optional object to be passed to the <create> method.
+     * update - {Object} Optional object to be passed to the <update> method.
+     * delete - {Object} Optional object to be passed to the <delete> method.
+     * callback - {Function} Optional function to be called when the commit
+     *     is complete.
+     * scope - {Object} Optional object to be set as the scope of the callback.
+     *
+     * Returns:
+     * {Array(<OpenLayers.Protocol.Response>)} An array of response objects,
+     *     one per request made to the server, each object's "priv" property
+     *     references the corresponding HTTP request.
+     */
+    commit: function(features, options) {
+        options = OpenLayers.Util.applyDefaults(options, this.options || {});
+        var resp = [], nResponses = 0;
+        
+        // Divide up features before issuing any requests.  This properly
+        // counts requests in the event that any responses come in before
+        // all requests have been issued.
+        var types = {};
+        types[OpenLayers.State.INSERT] = [];
+        types[OpenLayers.State.UPDATE] = [];
+        types[OpenLayers.State.DELETE] = [];
+        var feature, list;
+        for (var i=0, len=features.length; i<len; ++i) {
+            feature = features[i];
+            list = types[feature.state];
+            if(list) {
+                list.push(feature);
+            }
+        }
+        // tally up number of requests
+        var nRequests = (types[OpenLayers.State.INSERT].length > 0 ? 1 : 0) +
+            types[OpenLayers.State.UPDATE].length +
+            types[OpenLayers.State.DELETE].length;
+        
+        var success = true;
+        var finalResponse = new OpenLayers.Protocol.Response({
+            reqFeatures: features
+        });
+        finalResponse.insertIds = new Array(types[OpenLayers.State.INSERT].length);
+        function insertCallback(index) {
+            return function(response) {
+                finalResponse.insertIds[index] = response.priv.result && response.priv.result.insertId;
+                callback.apply(this, [response]);
+            }
+        }
+        function callback(response) {
+            this.callUserCallback(response, options);
+            success = success && response.success();
+            nResponses++;
+            if (nResponses >= nRequests) {
+                if (options.callback) {
+                    finalResponse.code = success ?
+                        OpenLayers.Protocol.Response.SUCCESS :
+                        OpenLayers.Protocol.Response.FAILURE;
+                    options.callback.apply(options.scope, [finalResponse]);
+                }
+            }
+        }
+        
+        // start issuing requests
+        var queue = types[OpenLayers.State.INSERT];
+        for (var i=queue.length-1; i>=0; --i) {
+            resp.push(this.create(
+                queue[i], OpenLayers.Util.applyDefaults(
+                    {callback: insertCallback(i), scope: this},
+                    options.create
+                )
+            ));
+        }
+        queue = types[OpenLayers.State.UPDATE];
+        for (var i=queue.length-1; i>=0; --i) {
+            resp.push(this.update(
+                queue[i], OpenLayers.Util.applyDefaults(
+                    {callback: callback, scope: this}, 
+                    options.update
+                ))
+            );
+        }
+        queue = types[OpenLayers.State.DELETE];
+        for (var i=queue.length-1; i>=0; --i) {
+            resp.push(this["delete"](
+                queue[i], OpenLayers.Util.applyDefaults(
+                    {callback: callback, scope: this},
+                    options["delete"]
+                ))
+            );
+        }
+        return resp;
+    },
+
+    /**
+     * Method: callUserCallback
+     * This method is used from within the commit method each time an
+     *     an transaction completes, it is responsible for calling the
+     *     user-supplied callbacks.
+     *
+     * Parameters:
+     * resp - {<OpenLayers.Protocol.Response>}
+     * options - {Object} The map of options passed to the commit call.
+     */
+    callUserCallback: function(resp, options) {
+        var opt = options[resp.requestType];
+        if (opt && opt.callback) {
+            opt.callback.call(opt.scope, resp);
+        }
+    },
+
+    
+    CLASS_NAME: "OpenLayers.Protocol.WebSQL"
+});    
+

Modified: sandbox/jgrocha/openlayers/lib/OpenLayers.js
===================================================================
--- sandbox/jgrocha/openlayers/lib/OpenLayers.js	2011-02-24 16:35:45 UTC (rev 11433)
+++ sandbox/jgrocha/openlayers/lib/OpenLayers.js	2011-02-24 16:43:16 UTC (rev 11434)
@@ -243,7 +243,7 @@
                 "OpenLayers/Protocol/HTTP.js",
                 "OpenLayers/Protocol/SQL.js",
                 "OpenLayers/Protocol/SQL/Gears.js",
-                "OpenLayers/Protocol/SQL/LocalSQL.js",
+                "OpenLayers/Protocol/SQL/WebSQL.js",
                 "OpenLayers/Protocol/WFS.js",
                 "OpenLayers/Protocol/WFS/v1.js",
                 "OpenLayers/Protocol/WFS/v1_0_0.js",



More information about the Commits mailing list