How to use the new factory property on the Table class - pranavh/AS3SQLite GitHub Wiki
Note: This was previously (and still is) doable by setting the itemClass
for a SQLStatement
. This way eliminates the need to set the itemClass
manually every single time.
So I've just added a factory
property to the Table
class. How do you use it? It's pretty simple.
The factory
is a variable of the Class
type. This means you can create a class and assign it to factory.
Consider you have created the following table:
var t:Table=new Table("Members");
t.ifNotExists=true;
t.addColumn("MemberID", "integer").addPKey(true, true);
t.addColumn("MName", "text").addNullable(false);
t.addColumn("MURL", "text").addNullable(false);
t.addColumn("MType", "integer").addDefault(ValueType.NUMBER, "0");
t.addColumn("IPAddr", "text").addNullable(true);
t.addColumn("Login", "text").addNullable(false);
t.addColumn("Password", "text").addNullable(false);
How do you use the factory? Very simple. Create a class called MemberFactory
public class MemberFactory {
public function MemberFactory() {}
public var MemberID:int, MName:String, MURL:String, MType:int, IPAddr:String, Login:String, Password:String;
}
and set
t.factory=MemberFactory;
Then when you execute the selectAllStatement, bingo! your returned values are automatically cast as MemberFactory
objects.
REMEMBER: The properties of MemberFactory
must be same as the column names in the table.
What's the use of this? Well, for one, it gives you strongly typed objects, widely known as a better coding practice.
Another use is that you can write code to easily generate the update and delete parameters. for example,
public function asDBParams():Object {
var obj:Object = {
"@MName": this.MName,
"@MURL": this.MURL,
"@MType": this.MType,
"@IPAddr": this.IPAddr,
"@Login": this.Login,
"@Password": this.Password
}
if(this.MemberID > 0)
obj["@MemberID"]=this.MemberID;
}
And you get the insert and update statements like:
var m:MemberFactory; //is an object of our factory
t.asInsertStatement(m.asDBParams()); //If MemberID is 0 or less, it is assumed to be an Insert statement, and the MemberID is not passed to the statement.
t.asUpdateStatement("MemberID=@MemberID", m.asDBParams()); //MemberID is greater than 0, so update this member, supply the where clause as partameterized.