blib/lib/LabKey/Query.pm

filter: Statementstmt 16.2% 40 / 246 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 57.1% 12 / 21 Podpod 0.0% 0 / 5 totaltotal 10.5% 52 / 495 CC 87 SCAR 60.8
CC
87
Cov
9%
_readrc
1122.0
selectRows
306.0
executeSql
156.0
CRAP 435.4
↑ Summary Build »
1 #!/usr/bin/perl
2  
3 =head1 NAME
4  
5 LabKey::Query
6  
7 =head1 SYNOPSIS
8  
9 use LabKey::Query;
10 my $results = LabKey::Query::selectRows(
11 -baseUrl => 'http://labkey.com:8080/labkey/',
12 -containerPath => 'myFolder/',
13 -schemaName => 'lists',
14 -queryName => 'mid_tags',
15 );
16
17 =head1 ABSTRACT
18  
19 For interacting with data in LabKey Server
20  
21 =head1 DESCRIPTION
22  
23 This module is designed to simplify querying and manipulating data in LabKey Server. It should more or less replicate the javascript APIs of the same names.
24  
25 After the module is installed, if you need to login with a specific user you
26 will need to create a .netrc file in the home directory of the user
27 running the perl script. Documentation on .netrc can be found here:
28 https://www.labkey.org/wiki/home/Documentation/page.view?name=netrc
29  
30 In API versions 0.08 and later, you can specify the param '-loginAsGuest'
31 which will query the server without any credentials. The server must permit
32 guest to that folder for this to work though.
33  
34 =head1 SEE ALSO
35  
36 The LabKey client APIs are described in greater detail here:
37 https://www.labkey.org/wiki/home/Documentation/page.view?name=viewAPIs
38  
39 Support questions should be directed to the LabKey forum:
40 https://www.labkey.org/announcements/home/Server/Forum/list.view?
41  
42 =head1 AUTHOR
43  
44 LabKey Software C<info@labkey.com>
45  
46 =head1 CONTRIBUTING
47  
48 Send comments, suggestions and bug reports to:
49  
50 L<https://www.labkey.org/project/home/Developer/Forum/begin.view>
51  
52  
53 =head1 COPYRIGHT
54
55 Copyright (c) 2010 Ben Bimber
56 Copyright (c) 2011-2013 LabKey Software
57  
58 Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
59  
60 =cut
61  
62 package LabKey::Query;
63  
64 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 1 ▶use FileHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
68 1 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
69 1 ▶use File::HomeDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
71  
72  
73 # Force all SSL connections to use TLSv1 or greater protocol. This is required for
74 # MacOSX and older Windows workstations.
75 #
76 # Credit to @chrisrth on stackoverflow (http://stackoverflow.com/a/20305596)
77 # See https://www.labkey.org/issues/home/Developer/issues/details.view?issueId=22146
78 # for more information.
79 #
80 1 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
81 1 my $context = new IO::Socket::SSL::SSL_Context(
82 SSL_version => 'tlsv1'
83 );
84 1 IO::Socket::SSL::set_default_context($context);
85  
86 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
87 1 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
88 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
89  
90  
91 1 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
92  
93 1 our $VERSION = "1.05";
94  
95  
96  
97 =head1 selectRows()
98  
99 selectRows() can be used to query data from LabKey server
100  
101 The following are the minimum required params:
102
103 my $results = LabKey::Query::selectRows(
104 -baseUrl => 'http://labkey.com:8080/labkey/',
105 -containerPath => 'myFolder/',
106 -schemaName => 'lists',
107 -queryName => 'mid_tags',
108 );
109  
110 The following are optional:
111  
112 -viewName => 'view1',
113 -filterArray => [
114 ['file_active', 'eq', 1],
115 ['species', 'neq', 'zebra']
116 ], #allows filters to be applied to the query similar to the labkey Javascript API.
117 -parameters => [
118 ['enddate', '2011/01/01'],
119 ['totalDays', 15]
120 ], #allows parameters to be applied to the query similar to the labkey Javascript API.
121 -maxRows => 10 #the max number of rows returned
122 -sort => 'ColumnA,ColumnB' #sort order used for this query
123 -offset => 100 #the offset used when running the query
124 -columns => 'ColumnA,ColumnB' #A comma-delimited list of column names to include in the results.
125 -containerFilterName => 'currentAndSubfolders'
126 -debug => 1, #will result in a more verbose output
127 -loginAsGuest => #will not attempt to lookup credentials in netrc
128 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
129 -requiredVersion => 9.1 #if 8.3 is selected, it will use LabKey's pre-9.1 format for returning the data. 9.1 is the default. See documentation of LABKEY.Query.ExtendedSelectRowsResults for more detail here:
130 https://www.labkey.org/download/clientapi_docs/javascript-api/symbols/LABKEY.Query.html
131 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
132 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
133
134 NOTE:
135  
136 - In version 1.0 and later of the perl API, the default result format is 9.1. This is different from the LabKey JS, which defaults to the earlier format for legacy purposes.
137 - The environment variable 'LABKEY_URL' can be used instead of supplying a '-baseUrl' param
138 - The environment variable 'LABKEY_NETRC' can be used to specify an alternate location of a netrc file, if not in the user's home directory.
139  
140 =cut
141  
142 sub selectRows {
143  
144 0 ▶ my %args = @_;
Subroutine selectRows: not called CC=17 SCAR=57.2
Pod undocumented
145
146 #allow baseUrl as environment variable
147 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
148
149 #sanity checking
150 0 my @required = ( '-containerPath', '-queryName', '-schemaName', '-baseUrl' );
151 0 foreach (@required) {
152 0 ▶ if ( !$args{$_} ) { croak("ERROR: Missing required param: $_") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
153 }
154  
155 my $url = URI->new(
156 _normalizeSlash($args{'-baseUrl'})
157 . "query/"
158 0 . _normalizeSlash($args{'-containerPath'})
159 . "getQuery.api?"
160 );
161
162 #if no machine supplied, extract domain from baseUrl
163 0 ▶ if (!$args{'-machine'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
164 0 $args{'-machine'} = $url->host;
165 }
166  
167 0 my $lk_config;
168 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
169 0 ▶ if(!$args{'-loginAsGuest'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-loginAsGuest"}) 0 0 0
170 0 $lk_config = _readrc( $args{-machine}, $netrc_file );
171 }
172
173 my %params = (
174 schemaName => $args{'-schemaName'},
175 "query.queryName" => $args{'-queryName'},
176 0 ▶ apiVersion => $args{'-requiredVersion'} || 9.1,
Condition0%0/2
$args{'-requiredVersion'} || 9.1
l!l
00
MC/DC0%0/1
$args{'-requiredVersion'} || 9.1
$args{'-requiredVersion'}
Truth table0%0/2
A
A= $args{'-requiredVersion'}
Aresult
11
00
177 );
178  
179 0 foreach ( @{ $args{-filterArray} } ) {
180 0 $params{"query." . @{$_}[0] . "~" . @{$_}[1]} = @{$_}[2] ;
181 }
182  
183 0 foreach ( @{ $args{-parameters} } ) {
184 0 $params{"query.param." . @{$_}[0]} = @{$_}[1];
185 }
186
187 0 foreach ('viewName', 'offset', 'sort', 'maxRows', 'columns', 'containerFilterName'){
188 0 ▶ if ( $args{'-'.$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-' . $_}) 0 0 0
189 0 $params{"query.".$_} = $args{'-'.$_};
190 }
191 }
192
193 0 $url->query_form(%params);
194
195 0 ▶ print $url."\n" if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
196  
197 #Fetch the actual data from the query
198 0 my $request = HTTP::Request->new( "GET" => $url );
199 0 ▶ if($lk_config){
Branch: 1 branch
BranchTrueFalseTotal
if ($lk_config) 0 0 0
200 0 $request->authorization_basic( $$lk_config{'login'}, $$lk_config{'password'} );
201 }
202 0 ▶ my $ua = $args{'-useragent'} || _createUserAgent( %args );
Condition0%0/3
$args{'-useragent'} || &_createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || &_createUserAgent(%args)
$args{'-useragent'} &_createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= &_createUserAgent(%args)
ABresult
1X1
011
000
203 0 my $response = $ua->request($request);
204  
205 # Simple error checking
206 0 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 0 0
207 0 croak( $response->status_line );
208 }
209  
210 0 ▶ my $json_obj = JSON->new->utf8->decode( $response->content )
Condition0%0/3
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
l!l&&r!l&&!r
000
MC/DC0%0/2
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
'JSON'->new->utf8->decode($response->content) croak("ERROR: Unable to decode JSON.\n$url\n")
Truth table0%0/3
A || B
A= 'JSON'->new->utf8->decode($response->content)B= croak("ERROR: Unable to decode JSON.\n$url\n")
ABresult
1X1
011
000
211 || croak("ERROR: Unable to decode JSON.\n$url\n");
212  
213 0 return $json_obj;
214  
215 }
216  
217  
218 =head1 insertRows()
219  
220 insertRows() can be used to insert records into a LabKey table
221  
222 The following are the minimum required params:
223  
224 my $insert = LabKey::Query::insertRows(
225 -baseUrl => 'http://labkey.com:8080/labkey/',
226 -containerPath => 'myFolder/',
227 -schemaName => 'lists',
228 -queryName => 'backup',
229 -rows => [{
230 "JobName" => 'jobName',
231 "Status" => $status,
232 "Log" => $log,
233 "Date" => $date
234 }],
235 );
236
237 The following are optional:
238  
239 -debug => 1, #will result in a more verbose output
240 -loginAsGuest => #will not attempt to lookup credentials in netrc
241 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
242 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
243 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
244  
245 NOTE:
246 - The environment variable 'LABKEY_URL' can be used instead of supplying a '-baseUrl' param
247 - The environment variable 'LABKEY_NETRC' can be used to specify an alternate location of a netrc file, if not in the user's home directory
248  
249 =cut
250  
251 sub insertRows {
252 0 ▶ my %args = @_;
Subroutine insertRows: not called CC=9 SCAR=45.0
Pod undocumented
253  
254 #allow baseUrl as an environment variable
255 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
256  
257 #sanity checking
258 0 my @required = ( '-containerPath', '-queryName', '-schemaName', '-baseUrl', '-rows' );
259 0 foreach (@required) {
260 0 ▶ if ( !$args{$_} ) { croak("ERROR: Missing required param: $_") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
261 }
262  
263 #if no machine supplied, extract domain from baseUrl
264 0 ▶ if (!$args{'-machine'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
265 0 my $url = URI->new($args{'-baseUrl'});
266 0 $args{'-machine'} = $url->host;
267 }
268
269 0 my $lk_config;
270 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
271 0 ▶ if(!$args{'-loginAsGuest'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-loginAsGuest"}) 0 0 0
272 0 $lk_config = _readrc( $args{-machine}, $netrc_file );
273 }
274  
275 my $url =
276 _normalizeSlash($args{'-baseUrl'})
277 . "query/"
278 0 . _normalizeSlash($args{'-containerPath'})
279 . "insertRows.api";
280  
281 0 ▶ print $url."\n" if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
282  
283 my $data = {
284 "schemaName" => $args{'-schemaName'},
285 "queryName" => $args{'-queryName'},
286 0 "rows" => $args{'-rows'}
287 };
288  
289 0 ▶ my $ua = $args{'-useragent'} || _createUserAgent( %args );
Condition0%0/3
$args{'-useragent'} || &_createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || &_createUserAgent(%args)
$args{'-useragent'} &_createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= &_createUserAgent(%args)
ABresult
1X1
011
000
290 0 my $response = _postData($ua, $url, $data, $lk_config);
291 0 return $response;
292  
293 }
294  
295  
296 =head1 updateRows()
297  
298 updateRows() can be used to update records in a LabKey table
299  
300 The following are the minimum required params:
301  
302 my $update = LabKey::Query::updateRows(
303 -baseUrl => 'http://labkey.com:8080/labkey/',
304 -containerPath => 'myFolder/',
305 -schemaName => 'lists',
306 -queryName => 'backup',
307 -rows => [{
308 "JobName" => 'jobName',
309 "Status" => $status,
310 "Log" => $log,
311 "Date" => $date
312 }],
313 );
314
315 The following are optional:
316  
317 -debug => 1, #will result in a more verbose output
318 -loginAsGuest => #will not attempt to lookup credentials in netrc
319 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
320 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
321 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
322  
323 NOTE:
324 - The environment variable 'LABKEY_URL' can be used instead of supplying a '-baseUrl' param
325 - The environment variable 'LABKEY_NETRC' can be used to specify an alternate location of a netrc file, if not in the user's home directory
326
327 =cut
328  
329 sub updateRows {
330 0 ▶ my %args = @_;
Subroutine updateRows: not called CC=9 SCAR=45.0
Pod undocumented
331  
332 #allow baseUrl as environment variable
333 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
334  
335 #sanity checking
336 0 my @required = ( '-containerPath', '-queryName', '-schemaName', '-baseUrl', '-rows' );
337 0 foreach (@required) {
338 0 ▶ if ( !$args{$_} ) { croak("ERROR: Missing required param: $_") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
339 }
340  
341 #if no machine supplied, extract domain from baseUrl
342 0 ▶ if (!$args{'-machine'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
343 0 my $url = URI->new($args{'-baseUrl'});
344 0 $args{'-machine'} = $url->host;
345 }
346 0 my $lk_config;
347 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
348 0 ▶ if(!$args{'-loginAsGuest'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-loginAsGuest"}) 0 0 0
349 0 $lk_config = _readrc( $args{-machine}, $netrc_file );
350 }
351  
352 my $url =
353 _normalizeSlash($args{'-baseUrl'})
354 . "query/"
355 0 . _normalizeSlash($args{'-containerPath'})
356 . "updateRows.api";
357  
358 0 ▶ print $url."\n" if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
359  
360 my $data = {
361 "schemaName" => $args{'-schemaName'},
362 "queryName" => $args{'-queryName'},
363 0 "rows" => $args{'-rows'}
364 };
365  
366 0 ▶ my $ua = $args{'-useragent'} || _createUserAgent( %args );
Condition0%0/3
$args{'-useragent'} || &_createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || &_createUserAgent(%args)
$args{'-useragent'} &_createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= &_createUserAgent(%args)
ABresult
1X1
011
000
367 0 my $response = _postData($ua, $url, $data, $lk_config);
368 0 return $response;
369  
370 }
371  
372  
373 =head1 deleteRows()
374  
375 deleteRows() can be used to delete records in a LabKey table
376  
377 The following are the minimum required params:
378  
379 my $update = LabKey::Query::deleteRows(
380 -baseUrl => 'http://labkey.com:8080/labkey/',
381 -containerPath => 'myFolder/',
382 -schemaName => 'lists',
383 -queryName => 'backup',
384 -rows => [{
385 "Key" => '12',
386 }],
387 );
388
389 The following are optional:
390  
391 -debug => 1, #will result in a more verbose output
392 -loginAsGuest => #will not attempt to lookup credentials in netrc
393 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
394 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
395 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
396  
397 NOTE:
398 - The environment variable 'LABKEY_URL' can be used instead of supplying a '-baseUrl' param
399 - The environment variable 'LABKEY_NETRC' can be used to specify an alternate location of a netrc file, if not in the user's home directory
400
401 =cut
402  
403 sub deleteRows {
404 0 ▶ my %args = @_;
Subroutine deleteRows: not called CC=9 SCAR=45.0
Pod undocumented
405  
406 #allow baseUrl as environment variable
407 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
408  
409 #sanity checking
410 0 my @required = ( '-containerPath', '-queryName', '-schemaName', '-baseUrl', '-rows' );
411 0 foreach (@required) {
412 0 ▶ if ( !$args{$_} ) { croak("ERROR: Missing required param: $_") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
413 }
414  
415 #if no machine supplied, extract domain from baseUrl
416 0 ▶ if (!$args{'-machine'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
417 0 my $url = URI->new($args{'-baseUrl'});
418 0 $args{'-machine'} = $url->host;
419 }
420 0 my $lk_config;
421 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
422 0 ▶ if(!$args{'-loginAsGuest'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-loginAsGuest"}) 0 0 0
423 0 $lk_config = _readrc( $args{-machine}, $netrc_file );
424 }
425  
426 my $url =
427 _normalizeSlash($args{'-baseUrl'})
428 . "query/"
429 0 . _normalizeSlash($args{'-containerPath'})
430 . "deleteRows.api";
431  
432 0 ▶ print $url."\n" if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
433  
434 my $data = {
435 "schemaName" => $args{'-schemaName'},
436 "queryName" => $args{'-queryName'},
437 0 "rows" => $args{'-rows'}
438 };
439  
440 0 ▶ my $ua = $args{'-useragent'} || _createUserAgent( %args );
Condition0%0/3
$args{'-useragent'} || &_createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || &_createUserAgent(%args)
$args{'-useragent'} &_createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= &_createUserAgent(%args)
ABresult
1X1
011
000
441 0 my $response = _postData($ua, $url, $data, $lk_config);
442 0 return $response;
443  
444 }
445  
446  
447 =head1 executeSql()
448  
449 executeSql() can be used to execute arbitrary SQL
450  
451 The following are the minimum required params:
452  
453 my $result = LabKey::Query::executeSql(
454 -baseUrl => 'http://labkey.com:8080/labkey/',
455 -containerPath => 'myFolder/',
456 -schemaName => 'study',
457 -sql => 'select MyDataset.foo, MyDataset.bar from MyDataset',
458 );
459
460 The following are optional:
461  
462 -maxRows => 10 #the max number of rows returned
463 -sort => 'ColumnA,ColumnB' #sort order used for this query
464 -offset => 100 #the offset used when running the query
465 -containerFilterName => 'currentAndSubfolders'
466 -debug => 1, #will result in a more verbose output
467 -loginAsGuest => #will not attempt to lookup credentials in netrc
468 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
469 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
470 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
471  
472 NOTE:
473 - The environment variable 'LABKEY_URL' can be used instead of supplying a '-baseUrl' param
474 - The environment variable 'LABKEY_NETRC' can be used to specify an alternate location of a netrc file, if not in the user's home directory
475
476 =cut
477  
478 sub executeSql {
479 0 ▶ my %args = @_;
Subroutine executeSql: not called CC=12 SCAR=50.5
Pod undocumented
480  
481 #allow baseUrl as environment variable
482 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
483  
484 #sanity checking
485 0 my @required = ( '-containerPath', '-baseUrl', '-sql' );
486 0 foreach (@required) {
487 0 ▶ if ( !$args{$_} ) { croak("ERROR: Missing required param: $_") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
488 }
489  
490 #if no machine supplied, extract domain from baseUrl
491 0 ▶ if (!$args{'-machine'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
492 0 my $url = URI->new($args{'-baseUrl'});
493 0 $args{'-machine'} = $url->host;
494 }
495 0 my $lk_config;
496 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
497 0 ▶ if(!$args{'-loginAsGuest'}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-loginAsGuest"}) 0 0 0
498 0 $lk_config = _readrc( $args{-machine}, $netrc_file );
499 }
500  
501 my $url =
502 _normalizeSlash($args{'-baseUrl'})
503 . "query/"
504 0 . _normalizeSlash($args{'-containerPath'})
505 . "executeSql.api?";
506  
507 0 ▶ print $url."\n" if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
508
509 my $data = {
510 "schemaName" => $args{'-schemaName'},
511 0 "sql" => $args{'-sql'},
512 };
513
514 0 foreach ('offset', 'sort', 'maxRows', 'containerFilterName'){
515 0 ▶ if ( $args{'-'.$_} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-' . $_}) 0 0 0
516 0 $$data{$_} = $args{'-'.$_};
517 }
518 }
519
520 0 ▶ print Dumper($data) if $args{-debug};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"-debug"} 0 0 0
521
522 0 ▶ my $ua = $args{'-useragent'} || _createUserAgent( %args );
Condition0%0/3
$args{'-useragent'} || &_createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || &_createUserAgent(%args)
$args{'-useragent'} &_createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= &_createUserAgent(%args)
ABresult
1X1
011
000
523 0 my $response = _postData($ua, $url, $data, $lk_config);
524 0 return $response;
525  
526 }
527  
528  
529  
530  
531 # NOTE: this code adapted from Net::Netrc module. It was changed so alternate locations could be supplied for a .netrc file
532 sub _readrc() {
533  
534 0 ▶ my $host = shift || 'default';
Subroutine _readrc: not called CC=33 SCAR=70.2
Condition0%0/2
shift() || 'default'
l!l
00
MC/DC0%0/1
shift() || 'default'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
535 0 my $file = shift;
536  
537 #allow user to supply netrc location
538 0 ▶ if(!$file || !-e $file){
Branch: 1 branch
BranchTrueFalseTotal
unless ($file and -e $file) 0 0 0
Condition0%0/3
$file and -e $file
!ll&&!rl&&r
000
MC/DC0%0/2
$file and -e $file
$file -e $file
Truth table0%0/3
A and B
A= $fileB= -e $file
ABresult
0X0
100
111
539 0 $file = File::Spec->catfile( File::HomeDir::home(), '.netrc' );
540 }
541 0 ▶ if ( !-e $file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $file) 0 0 0
542 0 $file = File::Spec->catfile( File::HomeDir::home(), '_netrc' );
543 }
544  
545 0 my %netrc = ();
546 0 my ( $login, $pass, $acct ) = ( undef, undef, undef );
547 0 my $fh;
548 0 local $_;
549  
550 0 $netrc{default} = undef;
551  
552 # OS/2 and Win32 do not handle stat in a way compatable with this check :-(
553 0 ▶ unless ( $^O eq 'os2'
Branch: 1 branch
BranchTrueFalseTotal
unless ($^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O =~ /^cygwin/) 0 0 0
Condition0%0/9
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O =~ /^cygwin/
l!l&&r!l&&!r
000
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS"
l!l&&r!l&&!r
000
$^O eq "os2" or $^O eq "MSWin32"
l!l&&r!l&&!r
000
MC/DC0%0/4
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O =~ /^cygwin/
$^O eq "os2" $^O eq "MSWin32" $^O eq "MacOS" $^O =~ /^cygwin/
Truth table0%0/5
A or B or C or D
A= $^O eq "os2"B= $^O eq "MSWin32"C= $^O eq "MacOS"D= $^O =~ /^cygwin/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
554 || $^O eq 'MSWin32'
555 || $^O eq 'MacOS'
556 || $^O =~ /^cygwin/ )
557 {
558 0 my @stat = stat($file);
559  
560 0 ▶ if (@stat) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stat) 0 0 0
561 0 ▶ if ( $stat[2] & 077 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stat[2] & 63) 0 0 0
562 0 carp "Bad permissions: $file";
563 0 return;
564 }
565 0 ▶ if ( $stat[4] != $< ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stat[4] != $<) 0 0 0
566 0 carp "Not owner: $file";
567 0 return;
568 }
569 }
570 }
571  
572 0 ▶ if ( $fh = FileHandle->new( $file, "r" ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fh = "FileHandle"->new($file, "r")) 0 0 0
573 0 my ( $mach, $macdef, $tok, @tok ) = ( 0, 0 );
574  
575 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
576 0 ▶ undef $macdef if /\A\n\Z/;
Branch: 1 branch
BranchTrueFalseTotal
if /\A\n\Z/ 0 0 0
577  
578 0 ▶ if ($macdef) {
Branch: 1 branch
BranchTrueFalseTotal
if ($macdef) 0 0 0
579 0 push( @$macdef, $_ );
580 0 next;
581 }
582  
583 0 s/^\s*//;
584 0 chomp;
585  
586 0 ▶ while ( length && s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*// )
Branch: 1 branch
BranchTrueFalseTotal
if (length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//) 0 0 0
Condition0%0/3
length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
!ll&&!rl&&r
000
MC/DC0%0/2
length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
length $_ s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
Truth table0%0/3
A and B
A= length $_B= s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
ABresult
0X0
100
111
587 {
588 0 ( my $tok = $+ ) =~ s/\\(.)/$1/g;
589 0 push( @tok, $tok );
590 }
591  
592 TOKEN:
593 0 ▶ while (@tok) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tok) 0 0 0
594 0 ▶ if ( $tok[0] eq "default" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok[0] eq "default") 0 0 0
595 0 shift(@tok);
596 0 $mach = bless {};
597 0 $netrc{default} = [$mach];
598  
599 0 next TOKEN;
600 }
601  
602 last TOKEN
603 0 ▶ unless @tok > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @tok > 1 0 0 0
604  
605 0 $tok = shift(@tok);
606  
607 0 ▶ if ( $tok eq "machine" ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($tok eq 'machine') { } 0 0 0
elsif ($tok =~ /^(login|password|account)$/) { } 0 0 0
elsif ($tok eq 'macdef') { } 0 0 0
608 0 my $host = shift @tok;
609 0 $mach = { machine => $host };
610  
611 $netrc{$host} = []
612 0 ▶ unless exists( $netrc{$host} );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $netrc{$host} 0 0 0
613 0 push( @{ $netrc{$host} }, $mach );
614 }
615 elsif ( $tok =~ /^(login|password|account)$/ ) {
616 0 ▶ next TOKEN unless $mach;
Branch: 1 branch
BranchTrueFalseTotal
unless $mach 0 0 0
617 0 my $value = shift @tok;
618  
619 # Following line added by rmerrell to remove '/' escape char in .netrc
620 0 $value =~ s/\/\\/\\/g;
621 0 $mach->{$1} = $value;
622 }
623 elsif ( $tok eq "macdef" ) {
624 0 ▶ next TOKEN unless $mach;
Branch: 1 branch
BranchTrueFalseTotal
unless $mach 0 0 0
625 0 my $value = shift @tok;
626 $mach->{macdef} = {}
627 0 ▶ unless exists $mach->{macdef};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $mach->{"macdef"} 0 0 0
628 0 $macdef = $mach->{machdef}{$value} = [];
629 }
630 }
631 }
632 0 $fh->close();
633 }
634
635 0 my $auth = $netrc{$host}[0];
636  
637 #if no machine is specified and there is only 1 machine in netrc, we use that one
638 0 ▶ if (!$auth && length((keys %netrc))==1){
Branch: 1 branch
BranchTrueFalseTotal
if (not $auth and length keys %netrc == 1) 0 0 0
Condition0%0/3
not $auth and length keys %netrc == 1
!ll&&!rl&&r
000
MC/DC0%0/2
not $auth and length keys %netrc == 1
not $auth length keys %netrc == 1
Truth table0%0/3
not(A) and B
A= not $authB= length keys %netrc == 1
ABresult
0X0
100
111
639 0 $auth = $netrc{(keys %netrc)[0]}[0];
640 }
641  
642 0 ▶ warn("Unable to find entry for host: $host") unless $auth;
Branch: 1 branch
BranchTrueFalseTotal
unless $auth 0 0 0
643 0 ▶ warn("Missing password for host: $host") unless $auth->{password};
Branch: 1 branch
BranchTrueFalseTotal
unless $auth->{"password"} 0 0 0
644 0 ▶ warn("Missing login for host: $host") unless $auth->{login};
Branch: 1 branch
BranchTrueFalseTotal
unless $auth->{"login"} 0 0 0
645  
646 0 return $auth;
647 }
648  
649  
650 sub _normalizeSlash(){
651 0 ▶ my $containerPath = shift;
Subroutine _normalizeSlash: not called CC=1 SCAR=6.9
652
653 0 $containerPath =~ s/^\///;
654 0 $containerPath =~ s/\/$//;
655 0 $containerPath .= '/';
656 0 return $containerPath;
657 }
658  
659  
660 sub _postData(){
661 0 ▶ my ($ua, $url, $data, $lk_config) = @_;
Subroutine _postData: not called CC=3 SCAR=24.8
662
663 0 my $json_obj = JSON->new->utf8->encode($data);
664  
665 0 my $req = new HTTP::Request;
666 0 $req->method('POST');
667 0 $req->url($url);
668 0 $req->content_type('application/json');
669 0 $req->content($json_obj);
670 0 $req->authorization_basic( $$lk_config{'login'}, $$lk_config{'password'} );
671 0 my $response = $ua->request($req);
672  
673 # Simple error checking
674 0 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 0 0
675 0 croak($response->status_line);
676 }
677  
678 #print Dumper($response);
679 0 ▶ $json_obj = JSON->new->utf8->decode( $response->content )
Condition0%0/3
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
l!l&&r!l&&!r
000
MC/DC0%0/2
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
'JSON'->new->utf8->decode($response->content) croak("ERROR: Unable to decode JSON.\n$url\n")
Truth table0%0/3
A || B
A= 'JSON'->new->utf8->decode($response->content)B= croak("ERROR: Unable to decode JSON.\n$url\n")
ABresult
1X1
011
000
680 || croak("ERROR: Unable to decode JSON.\n$url\n");
681
682 0 return $json_obj;
683 }
684  
685 sub _createUserAgent() {
686 0 ▶ my %args = @_;
Subroutine _createUserAgent: not called CC=2 SCAR=17.9
687  
688 0 my $ua = new LWP::UserAgent;
689 0 $ua->agent("Perl API Client/1.0");
690 0 ▶ if ($args{'-timeout'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-timeout"}) 0 0 0
691 0 print "setting timeout to " . $args{'-timeout'} . "\n";
692 0 $ua->timeout($args{'-timeout'});
693 }
694 0 return $ua;
695 }
696  
697  
698 1 1;
699  
↑ Summary Build »