by cdshearer >> Mon, 16 Dec 2002 22:42:43 GMT
Hi All
Here's a little method I came up with that I thought I'd share.
I've always been frustrated by wanting to do a quick query on all instances of a class, and having to create a workspace method such as:
vars
oa : ObjectArray;
o : Object;
count : Integer;begin
create oa transient;
Customer.allInstances(oa, 0, true);
foreach o in oa where o.Customer.name = "" do
count := count + 1;
endforeach;
write count;
epilog
delete oa;
end;
and then select it and execute it.
Just think how much easier this would be in SQL:
SELECT COUNT(*) FROM Customer WHERE Name=""
So, I realised that I could add a method to the Class class. Here's the method:
countAllInstances(pWhereClause: String): Integer;
vars
whereClause,
notStr,
source : String;
errorCode,
errorPos,
errorLength : Integer;
meth : JadeMethod;begin
source := "
vars
oa : ObjectArray;
o : Object;
c : Integer;begin
create oa transient;
" & name & ".allInstances(oa, 0, true);
foreach o in oa ";
if pWhereClause <> null then
whereClause := pWhereClause.trimBlanks();
if whereClause[1:4].toUpper() = "NOT " then
whereClause := whereClause[4:end].trimBlanks();
notStr := "not ";
endif;
source := source & " where " & notStr & "o." & name & "." & whereClause; endif;
source := source &
" do
c := c + 1;
endforeach;
return c;
epilog
delete oa;
end;
";
meth := process.createTransientMethod("count", Class, currentSchema,
source, true, Integer,
errorCode, errorPos, errorLength);
if errorCode = 0 then
return process.executeTransientMethod(meth, self).Integer;
else
app.msgBox("Your where clause contains a syntax error!",
null, MsgBox_Stop_Icon);
return null;
endif;
epilog
if meth <> null then
process.deleteTransientMethod(meth);
endif;
end;
Now, to use this, just bring up a Workspace window, and type:
write Customer.countAllInstances('name = ""');
The method only handles simple expressions, and doesn't handle AND, OR, etc. It does detect a NOT in the expression and adjusts the code to handle this (so you can write 'not name=""'). However, if you were willing to write an interpreter, this could be expanded.
Easy huh? Obviously you wouldn't use this in production, but it certainly makes development situations convenient.
Enjoy!
Craig