Object Script query without using %OpenId

1k views Asked by At

How would I write this query in object script rather than SQL?

Query GetSessionIdByUserName(UserName As %String) As %SQLQuery [ Private ]
{
    SELECT %ID from Sample.Session
    WHERE UserName = :UserName
}

All I seem to find so far in the documentation is %OpenId

##class(Sample.Session).%OpenId(id)  

What happens when the id is not known and needs to be found first?

2

There are 2 answers

0
psr On BEST ANSWER

There aren't built in methods to do something like get the session ID by user name. You need to write them yourself, and SQL is probably usually the best way to do it. You can wrap the SQL in a method though, rather than a query.

Method GetSessionIdByUserName(UserName As %String) As Sample.Session [ Private ]

{
    &SQL(SELECT %ID INTO :ID from Sample.Session
    WHERE UserName = :UserName)

    Q ##class(Sample.Session).%OpenId(ID)
}
2
kazamatzuri On

If you insist on not using SQL, you would need to do something along the lines of:

Method GetSEssionIdByUserName(UserName as %String) As Sample.Session [ Private ]
{
   s c=$O(^Sample.SessionD("")),f=""
   while ((f="") && (c'="")){
       s p=##class(Sample.Session).%OpenId(c)
       if $isobject(p){
            s:p.UserName=UserName f=c
       }
       //alternatively if you're sure about the global structure, something like this:
       //assume the Username is stored at position 3 for a sec:
       //s:$LG(^Sample.SessionD(c),3)=UserName f=c

       s c=$O(^Sample.SessionD(c))
   }
   q ##class(Sample.Session).%OpenId(f)
}

You can make it even smarter and only open the session object once, but down the road I would suggest against going this way. It might look fancy, but in two years you won't know what you were doing. So I'd suggest to go with the embedded sql psr suggested, it's much more readable (and maintainable).