| 1 | package App::perlrdf::Command::QueryParse; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use utf8; | ||
| 7 | |||
| 8 | BEGIN { | ||
| 9 | $App::perlrdf::Command::QueryParse::AUTHORITY = 'cpan:TOBYINK'; | ||
| 10 | $App::perlrdf::Command::QueryParse::VERSION = '0.004'; | ||
| 11 | } | ||
| 12 | |||
| 13 | use base 'App::perlrdf::Command::Query'; | ||
| 14 | use namespace::clean; | ||
| 15 | |||
| 16 | use constant abstract => q (dumps SPARQL in other formats); | ||
| 17 | use constant command_names => qw( query_parse ); | ||
| 18 | use constant description => <<'DESCRIPTION'; | ||
| 19 | Output formats are: SSE (default), JSON, YAML, SPARQL. | ||
| 20 | DESCRIPTION | ||
| 21 | |||
| 22 | use constant opt_spec => ( | ||
| 23 | [ 'execute|e=s', 'Query to parse' ], | ||
| 24 | [ 'sparql-file|f=s', 'File containing query to parse' ], | ||
| 25 | []=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=> | ||
| 26 | [ 'output|o=s@', 'Output filename or URL' ], | ||
| 27 | [ 'output-spec|O=s@', 'Output file specification' ], | ||
| 28 | [ 'output-format|s=s', 'Output format (mnemonic: serialise)' ], | ||
| 29 | ); | ||
| 30 | |||
| 31 | sub validate_args | ||
| 32 | { | ||
| 33 | my ($self, $opt, $arg) = @_; | ||
| 34 | $self->usage_error("Must not provide both 'sparql_file' and 'execute' options.") | ||
| 35 | if exists $opt->{sparql_file} && exists $opt->{execute}; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub execute | ||
| 39 | { | ||
| 40 | require JSON; | ||
| 41 | require YAML::XS; | ||
| 42 | require RDF::Query; | ||
| 43 | |||
| 44 | my ($self, $opt, $arg) = @_; | ||
| 45 | |||
| 46 | my $sparql = $self->_sparql($opt, $arg); | ||
| 47 | my $query = RDF::Query::->new($sparql) | ||
| 48 | or die RDF::Query::->error; | ||
| 49 | |||
| 50 | my (@outputs) = $self->_outputs( | ||
| 51 | $opt, | ||
| 52 | $arg, | ||
| 53 | 'App::perlrdf::FileSpec::OutputFile', | ||
| 54 | ); | ||
| 55 | |||
| 56 | foreach my $out (@outputs) | ||
| 57 | { | ||
| 58 | my $str; | ||
| 59 | |||
| 60 | if ($out->format =~ /json/i) | ||
| 61 | { $str = JSON::to_json( $query->as_hash, {pretty=>1,canonical=>1} ) } | ||
| 62 | elsif ($out->format =~ /ya?ml/i) | ||
| 63 | { $str = YAML::XS::Dump( $query->as_hash ) } | ||
| 64 | elsif ($out->format =~ /sparql/i) | ||
| 65 | { $str = $query->as_sparql } | ||
| 66 | else | ||
| 67 | { $str = $query->sse } | ||
| 68 | |||
| 69 | $out->handle->print($str); | ||
| 70 | $out->handle->close; | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | 1; | ||
| 75 |