Merge lp:~paul-lucas/zorba/pjl-misc into lp:zorba

Proposed by Paul J. Lucas
Status: Merged
Approved by: Paul J. Lucas
Approved revision: 11425
Merged at revision: 11694
Proposed branch: lp:~paul-lucas/zorba/pjl-misc
Merge into: lp:zorba
Diff against target: 9065 lines (+3292/-3960)
80 files modified
bin/CMakeLists.txt (+3/-4)
bin/path_util.cpp (+0/-85)
bin/path_util.h (+0/-41)
bin/timers.cpp (+176/-0)
bin/timers.h (+73/-0)
bin/util.cpp (+0/-37)
bin/util.h (+25/-19)
bin/zorbacmd.cpp (+536/-971)
bin/zorbacmd_args.cpp (+783/-0)
bin/zorbacmd_props.cpp (+45/-199)
bin/zorbacmd_props.h (+101/-107)
bin/zorbacmdproperties.txt (+0/-40)
bin/zorbacmdproperties_base.cpp (+0/-374)
bin/zorbacmdproperties_base.h (+0/-142)
include/zorba/properties.h (+400/-0)
include/zorba/properties_base.h (+7/-130)
include/zorba/util/fs_util.h (+41/-0)
include/zorba/util/smart_ptr.h (+6/-0)
include/zorba/zorba.h (+14/-5)
src/api/CMakeLists.txt (+1/-0)
src/api/properties.cpp (+79/-366)
src/api/zorbaimpl.cpp (+3/-3)
src/api/zorbaimpl.h (+1/-1)
src/compiler/api/compiler_api.cpp (+2/-2)
src/compiler/api/compilercb.cpp (+11/-12)
src/compiler/codegen/plan_visitor.cpp (+6/-9)
src/compiler/expression/expr_base.cpp (+1/-1)
src/compiler/expression/expr_put.cpp (+3/-4)
src/compiler/parser/xquery_driver.cpp (+6/-5)
src/compiler/rewriter/framework/default_optimizer.cpp (+9/-9)
src/compiler/rewriter/framework/rule_driver.cpp (+3/-3)
src/compiler/rewriter/rules/flwor_rules.cpp (+2/-2)
src/compiler/rewriter/rules/index_join_rule.cpp (+2/-2)
src/compiler/rewriter/rules/index_matching_rule.cpp (+1/-1)
src/compiler/rewriter/rules/type_rules.cpp (+1/-1)
src/compiler/translator/translator.cpp (+10/-11)
src/diagnostics/zorba_exception.cpp (+15/-6)
src/functions/function_impl.h (+2/-2)
src/runtime/api/plan_wrapper.cpp (+2/-2)
src/runtime/base/plan_iterator.cpp (+2/-2)
src/runtime/full_text/apply.cpp (+3/-3)
src/runtime/full_text/ftcontains_visitor.cpp (+3/-3)
src/runtime/jsound/jsound_util.cpp (+2/-2)
src/runtime/spec/printer_visitor_cpp.xq (+15/-10)
src/runtime/visitors/pregenerated/printer_visitor.cpp (+3/-3)
src/runtime/visitors/printer_visitor_impl.cpp (+15/-15)
src/store/naive/CMakeLists.txt (+0/-1)
src/store/naive/properties.cpp (+0/-115)
src/store/naive/properties.h (+0/-74)
src/store/naive/store.cpp (+3/-8)
src/store/naive/store_properties.h (+0/-112)
src/store/naive/store_properties.txt (+0/-2)
src/system/CMakeLists.txt (+4/-3)
src/system/properties.cpp (+0/-182)
src/system/properties.h (+0/-126)
src/system/zorba_properties.h (+0/-145)
src/system/zorba_properties.txt (+0/-49)
src/unit_tests/test_stemmer.cpp (+1/-4)
src/unit_tests/test_thesaurus.cpp (+2/-5)
src/unit_tests/test_tokenizer.cpp (+1/-4)
src/util/fs_util.cpp (+16/-2)
src/zorbautils/CMakeLists.txt (+0/-1)
src/zorbautils/properties_base.cpp (+0/-192)
test/driver/testdriver.cpp (+0/-9)
test/driver/testdriver_common.cpp (+13/-10)
test/driver/testdriver_mt.cpp (+0/-4)
test/driver/updtestdriver.cpp (+0/-3)
test/extern/test_extern_func.cpp (+0/-4)
test/iterplans/CMakeLists.txt (+7/-1)
test/iterplans/apitest.cpp (+156/-239)
test/iterplans/apitest_args.cpp (+541/-0)
test/iterplans/apitest_props.cpp (+50/-0)
test/iterplans/apitest_props.h (+81/-0)
test/unit/context_item.cpp (+0/-4)
test/unit/ext_in_opt.cpp (+0/-4)
test/unit/main_sequential.cpp (+0/-4)
test/unit/no_folding.cpp (+0/-4)
test/unit/plan_serializer.cpp (+4/-9)
test/unit/staticcollectionmanager.cpp (+0/-4)
test/unit/streamable_string.cpp (+0/-2)
To merge this branch: bzr merge lp:~paul-lucas/zorba/pjl-misc
Reviewer Review Type Date Requested Status
Matthias Brantner Approve
Paul J. Lucas Approve
Review via email: mp+205515@code.launchpad.net

Commit message

Major clean-up of properties, zorbacmd, and apitest command-line arguments.

Description of the change

Major clean-up of properties, zorbacmd, and apitest command-line arguments.

To post a comment you must log in.
Revision history for this message
Paul J. Lucas (paul-lucas) :
review: Approve
Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "BuildZorbaUbuntu" failed.

Check compiler output at http://jenkins.zorba.io:8180/job/BuildZorbaUbuntu/513/parsed_console to view the results.

lp:~paul-lucas/zorba/pjl-misc updated
11426. By Paul J. Lucas

Fixed abort.

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "BuildZorbaUbuntu" failed.

Check compiler output at http://jenkins.zorba.io:8180/job/BuildZorbaUbuntu/514/parsed_console to view the results.

lp:~paul-lucas/zorba/pjl-misc updated
11427. By Paul J. Lucas

More fixes.

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "BuildZorbaUbuntu" failed.

Check compiler output at http://jenkins.zorba.io:8180/job/BuildZorbaUbuntu/515/parsed_console to view the results.

lp:~paul-lucas/zorba/pjl-misc updated
11428. By Paul J. Lucas

More fixes.

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "BuildZorbaUbuntu" failed.

Check compiler output at http://jenkins.zorba.io:8180/job/BuildZorbaUbuntu/516/parsed_console to view the results.

lp:~paul-lucas/zorba/pjl-misc updated
11429. By Paul J. Lucas

More fixes.

11430. By Paul J. Lucas

More fixes.

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "TestZorbaUbuntu" failed.
34 tests failed (8754 total tests run).

Check test results at http://jenkins.zorba.io:8180/job/TestZorbaUbuntu/454/testReport/ to view the results.

lp:~paul-lucas/zorba/pjl-misc updated
11431. By Paul J. Lucas

Added endl.

11432. By Paul J. Lucas

Memory fixes.

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Voting criteria failed for the following merge proposals:

https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515 :
Votes: {'Approve': 1}

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue result for https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Stage "CommitZorba" failed.

Check console output at http://jenkins.zorba.io:8180/job/CommitZorba/287/console to view the results.

Revision history for this message
Matthias Brantner (matthias-brantner) :
review: Approve
Revision history for this message
Matthias Brantner (matthias-brantner) :
review: Approve
Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue starting for the following merge proposals:
https://code.launchpad.net/~paul-lucas/zorba/pjl-misc/+merge/205515

Progress dashboard at http://jenkins.zorba.io:8180/view/ValidationQueue

Revision history for this message
Zorba Build Bot (zorba-buildbot) wrote :

Validation queue succeeded - proposal merged!

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'bin/CMakeLists.txt'
--- bin/CMakeLists.txt 2014-01-31 23:27:47 +0000
+++ bin/CMakeLists.txt 2014-02-11 00:42:47 +0000
@@ -44,11 +44,10 @@
44ENDIF (ZORBA_WITH_DEBUGGER)44ENDIF (ZORBA_WITH_DEBUGGER)
4545
46SET(SRCS46SET(SRCS
47 zorbacmd_args.cpp
48 zorbacmd_props.cpp
49 timers.cpp
47 zorbacmd.cpp50 zorbacmd.cpp
48 zorbacmdproperties_base.cpp
49 zorbacmdproperties.cpp
50 util.cpp
51 path_util.cpp
52)51)
5352
54ZORBA_GENERATE_EXE("zorbacmd" "${SRCS}" "" "zorba" "bin")53ZORBA_GENERATE_EXE("zorbacmd" "${SRCS}" "" "zorba" "bin")
5554
=== removed file 'bin/path_util.cpp'
--- bin/path_util.cpp 2013-05-31 03:38:45 +0000
+++ bin/path_util.cpp 1970-01-01 00:00:00 +0000
@@ -1,85 +0,0 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "path_util.h"
18
19#include <cstdlib>
20
21#include <zorba/static_context.h>
22#include <zorba/util/fs_util.h>
23
24#include "util.h"
25#include "zorbacmdproperties.h"
26
27namespace zorba {
28
29namespace PathUtil {
30
31void
32tokenizePath(
33 const std::string& aPathStr,
34 std::vector<String>& aResult)
35{
36 std::vector<std::string> lPath;
37#ifdef WIN32
38 Util::tokenize(aPathStr, ";", lPath);
39#else
40 Util::tokenize(aPathStr, ":", lPath);
41#endif
42 for (std::vector<std::string>::iterator lIter = lPath.begin();
43 lIter != lPath.end(); ++lIter) {
44 aResult.push_back(*lIter);
45 }
46}
47
48void
49setPathsOnContext(
50 const ZorbaCMDProperties& aProperties,
51 StaticContext_t& aStaticCtx)
52{
53 std::vector<String> lPath;
54 std::string lPathStr;
55
56 // Compute the current working directory to append to all paths.
57 std::string lCWD( fs::curdir() );
58
59 // setModulePaths() *overwrites* the URI path and lib path, so there's no
60 // sense in calling both. So if --module-path exists, just use it.
61 aProperties.getModulePath(lPathStr);
62 if (lPathStr.length() > 0) {
63 tokenizePath(lPathStr, lPath);
64 lPath.push_back(lCWD);
65 aStaticCtx->setModulePaths(lPath);
66 }
67 else {
68 // Compute and set URI path
69 aProperties.getURIPath(lPathStr);
70 tokenizePath(lPathStr, lPath);
71 lPath.push_back(lCWD);
72 aStaticCtx->setURIPath(lPath);
73 lPath.clear();
74
75 // Compute and set lib path
76 aProperties.getLibPath(lPathStr);
77 tokenizePath(lPathStr, lPath);
78 lPath.push_back(lCWD);
79 aStaticCtx->setLibPath(lPath);
80 }
81}
82
83} /* namespace ModulePath */
84
85} /* namespace zorba */
860
=== removed file 'bin/path_util.h'
--- bin/path_util.h 2013-02-07 17:24:36 +0000
+++ bin/path_util.h 1970-01-01 00:00:00 +0000
@@ -1,41 +0,0 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef ZORBA_MODULE_PATH_H
17#define ZORBA_MODULE_PATH_H
18
19#include <vector>
20#include <string>
21#include <zorba/api_shared_types.h>
22
23class ZorbaCMDProperties;
24
25namespace zorba {
26
27 class String;
28
29 namespace PathUtil {
30
31 void
32 setPathsOnContext(const ZorbaCMDProperties& aProperties,
33 zorba::StaticContext_t& aStaticCtx);
34
35 void
36 tokenizePath(const std::string& aPathStr, std::vector<String>& aResult);
37
38 }
39} /* namespace zorba */
40
41#endif
420
=== added file 'bin/timers.cpp'
--- bin/timers.cpp 1970-01-01 00:00:00 +0000
+++ bin/timers.cpp 2014-02-11 00:42:47 +0000
@@ -0,0 +1,176 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// local
18#include "timers.h"
19
20using namespace std;
21
22///////////////////////////////////////////////////////////////////////////////
23
24#define INIT_TIMER(KIND) \
25 elapsed_##KIND##_walltime( 0 ), \
26 elapsed_##KIND##_cputime( 0 )
27
28#define START_TIMER(KIND) \
29 zorba::time::get_current_walltime( start_##KIND##_walltime ); \
30 zorba::time::get_current_cputime( start_##KIND##_cputime )
31
32#define STOP_TIMER(KIND) \
33 zorba::time::get_current_walltime( stop_##KIND##_walltime ); \
34 elapsed_##KIND##_walltime += zorba::time::get_walltime_elapsed( start_##KIND##_walltime, stop_##KIND##_walltime ); \
35 zorba::time::get_current_cputime( stop_##KIND##_cputime ); \
36 elapsed_##KIND##_cputime += zorba::time::get_cputime_elapsed( start_##KIND##_cputime, stop_##KIND##_cputime )
37
38Timers::Timers( unsigned long num_execs ) :
39 num_execs_( num_execs ),
40 INIT_TIMER( init ),
41 INIT_TIMER( deinit ),
42 INIT_TIMER( comp ),
43 INIT_TIMER( exec ),
44 INIT_TIMER( load ),
45 INIT_TIMER( unload ),
46 INIT_TIMER( plan_save ),
47 INIT_TIMER( plan_load ),
48 INIT_TIMER( total )
49{
50}
51
52void Timers::startTimer( kind k, unsigned long iteration ) {
53 if ( iteration == 0 && num_execs_ > 1 )
54 return;
55 switch ( k ) {
56 case init:
57 START_TIMER( init );
58 break;
59 case deinit:
60 START_TIMER( deinit );
61 break;
62 case total:
63 START_TIMER( total );
64 break;
65 case comp:
66 START_TIMER( comp );
67 break;
68 case exec:
69 START_TIMER( exec );
70 break;
71 case unload:
72 START_TIMER( unload );
73 break;
74 case plan_save:
75 START_TIMER( plan_save );
76 break;
77 case plan_load:
78 START_TIMER( plan_load );
79 break;
80 } // switch
81}
82
83void Timers::stopTimer( kind k, unsigned long iteration ) {
84 if ( iteration == 0 && num_execs_ > 1 )
85 return;
86 switch ( k ) {
87 case init:
88 STOP_TIMER( init );
89 break;
90 case deinit:
91 STOP_TIMER( deinit );
92 break;
93 case total:
94 STOP_TIMER( total );
95 break;
96 case comp:
97 STOP_TIMER( comp );
98 break;
99 case exec:
100 STOP_TIMER( exec );
101 break;
102 case unload:
103 STOP_TIMER( unload );
104 break;
105 case plan_save:
106 STOP_TIMER( plan_save );
107 break;
108 case plan_load:
109 STOP_TIMER( plan_load );
110 break;
111 } // switch
112}
113
114ostream& Timers::print( ostream &os, bool serializePlan ) {
115 os.precision( 3 );
116 os.setf( ios::fixed );
117
118 os << "\nNumber of executions = " << num_execs_ << endl;
119
120 unsigned long timeDiv = num_execs_ == 1 ? 1 : (num_execs_ - 1);
121 double cWalltime = elapsed_comp_walltime / timeDiv;
122 double eWalltime = elapsed_exec_walltime / timeDiv;
123 double lWalltime = elapsed_load_walltime / timeDiv;
124 double uWalltime = elapsed_unload_walltime / timeDiv;
125 double psWalltime = elapsed_plan_save_walltime / timeDiv;
126 double plWalltime = elapsed_plan_load_walltime / timeDiv;
127 double tWalltime = elapsed_total_walltime / timeDiv;
128
129 double cCputime = elapsed_comp_cputime / timeDiv;
130 double eCputime = elapsed_exec_cputime / timeDiv;
131 double lCputime = elapsed_load_cputime / timeDiv;
132 double uCputime = elapsed_unload_cputime / timeDiv;
133 double psCputime = elapsed_plan_save_cputime / timeDiv;
134 double plCputime = elapsed_plan_load_cputime / timeDiv;
135 double tCputime = elapsed_total_cputime / timeDiv;
136
137 os << "Engine Startup Time : " << elapsed_init_walltime
138 << " (user: " << elapsed_init_cputime << ")"
139 << " milliseconds" << endl;
140
141 os << "Average Compilation Time: " << cWalltime
142 << " (user: " << cCputime << ")"
143 << " milliseconds" << endl;
144
145 if ( serializePlan ) {
146 os << "Average Plan Saving Time: " << psWalltime
147 << " (user: " << psCputime << ")"
148 << " milliseconds" << endl;
149
150 os << "Average Plan Loading Time: " << plWalltime
151 << " (user: " << plCputime << ")"
152 << " milliseconds" << endl;
153 }
154
155 os << "Average Execution Time : " << eWalltime - lWalltime
156 << " (user: " << eCputime - lCputime << ")"
157 << " milliseconds" << endl;
158
159 os << "Average Loading Time : " << lWalltime
160 << " (user: " << lCputime << ")"
161 << " milliseconds" << endl;
162
163 os << "Average Unloading Time : " << uWalltime
164 << " (user: " << uCputime << ")"
165 << " milliseconds" << endl;
166
167 os << "Average Total Time : " << tWalltime
168 << " (user: " << tCputime << ")"
169 << " milliseconds" << endl;
170
171 return os;
172}
173
174///////////////////////////////////////////////////////////////////////////////
175
176/* vim:set et sw=2 ts=2: */
0177
=== added file 'bin/timers.h'
--- bin/timers.h 1970-01-01 00:00:00 +0000
+++ bin/timers.h 2014-02-11 00:42:47 +0000
@@ -0,0 +1,73 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ZORBA_CMD_TIMERS_H
18#define ZORBA_CMD_TIMERS_H
19
20// standard
21#include <iostream>
22
23// Zorba
24#include <zorba/util/time.h>
25
26///////////////////////////////////////////////////////////////////////////////
27
28#define DECLARE_TIMER(KIND) \
29 zorba::time::walltime start_##KIND##_walltime; \
30 zorba::time::walltime stop_##KIND##_walltime; \
31 zorba::time::cputime start_##KIND##_cputime; \
32 zorba::time::cputime stop_##KIND##_cputime; \
33 double elapsed_##KIND##_walltime; \
34 double elapsed_##KIND##_cputime
35
36struct Timers {
37 enum kind {
38 init,
39 deinit,
40 comp,
41 exec,
42 unload,
43 plan_save,
44 plan_load,
45 total
46 };
47
48 unsigned long num_execs_;
49
50 DECLARE_TIMER( init );
51 DECLARE_TIMER( deinit );
52 DECLARE_TIMER( comp );
53 DECLARE_TIMER( exec );
54 DECLARE_TIMER( load );
55 DECLARE_TIMER( unload );
56 DECLARE_TIMER( plan_save );
57 DECLARE_TIMER( plan_load );
58 DECLARE_TIMER( total );
59
60 Timers( unsigned long num_execs );
61
62 void startTimer( kind, unsigned long iteration );
63 void stopTimer( kind, unsigned long iteration );
64
65 std::ostream& print( std::ostream&, bool );
66};
67
68#undef DECLARE_TIMER
69
70///////////////////////////////////////////////////////////////////////////////
71
72#endif /* ZORBA_CMD_TIMERS_H */
73/* vim:set et sw=2 ts=2: */
074
=== removed file 'bin/util.cpp'
--- bin/util.cpp 2013-02-07 17:24:36 +0000
+++ bin/util.cpp 1970-01-01 00:00:00 +0000
@@ -1,37 +0,0 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "util.h"
18
19namespace zorba {
20
21 void
22 Util::tokenize(const std::string& str,
23 const std::string& delimiters,
24 std::vector<std::string>& tokens)
25 {
26 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
27
28 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
29
30 while (std::string::npos != pos || std::string::npos != lastPos) {
31 tokens.push_back(str.substr(lastPos, pos - lastPos));
32 lastPos = str.find_first_not_of(delimiters, pos);
33 pos = str.find_first_of(delimiters, lastPos);
34 }
35 }
36
37} /* namespace zorba */
380
=== modified file 'bin/util.h'
--- bin/util.h 2013-02-07 17:24:36 +0000
+++ bin/util.h 2014-02-11 00:42:47 +0000
@@ -13,23 +13,29 @@
13 * See the License for the specific language governing permissions and13 * See the License for the specific language governing permissions and
14 * limitations under the License.14 * limitations under the License.
15 */15 */
16#ifndef ZORBA_UTIL_H16
17#define ZORBA_UTIL_H17#ifndef ZORBA_CMD_UTIL_H
1818#define ZORBA_CMD_UTIL_H
19
20#include <string>
19#include <vector>21#include <vector>
20#include <string>22
2123///////////////////////////////////////////////////////////////////////////////
22namespace zorba {24
2325template<class InStringType,class OutStringType>
24 class Util {26void tokenize( InStringType const &s, char delim,
25 public:27 std::vector<OutStringType> *tokens ) {
26 static void28 typename InStringType::size_type last_pos = s.find_first_not_of( delim, 0 );
27 tokenize(const std::string& str,29 typename InStringType::size_type pos = s.find_first_of( delim, last_pos );
28 const std::string& delimiters,30
29 std::vector<std::string>& tokens);31 while ( pos != InStringType::npos || last_pos != InStringType::npos ) {
3032 tokens->push_back( s.substr( last_pos, pos - last_pos ).c_str() );
31 };33 last_pos = s.find_first_not_of( delim, pos );
32} /* namespace zorba */34 pos = s.find_first_of( delim, last_pos );
3335 }
34#endif36}
3537
38///////////////////////////////////////////////////////////////////////////////
39
40#endif /* ZORBA_CMD_UTIL_H */
41/* vim:set et sw=2 ts=2: */
3642
=== modified file 'bin/zorbacmd.cpp'
--- bin/zorbacmd.cpp 2013-09-17 21:12:49 +0000
+++ bin/zorbacmd.cpp 2014-02-11 00:42:47 +0000
@@ -14,34 +14,34 @@
14 * limitations under the License.14 * limitations under the License.
15 */15 */
1616
17#include "zorbacmdproperties.h"17// standard
1818#include <cassert>
19#include <fstream>
19#include <iostream>20#include <iostream>
20#include <fstream>
21#include <sstream>21#include <sstream>
22#include <string>
22#include <vector>23#include <vector>
23#include <string>
24#include <cassert>
2524
26#ifdef WIN3225#ifdef WIN32
27#include <windows.h>26#include <windows.h>
28#define sleep(s) Sleep(s*1000)27#endif /* WIN32 */
29#endif
3028
31#include <zorba/zorba.h>29// Zorba
32#include <zorba/zorba_exception.h>30#include <zorba/audit.h>
33#include <zorba/xquery_exception.h>31#include <zorba/audit_scoped.h>
34#include <zorba/document_manager.h>32#include <zorba/document_manager.h>
33#include <zorba/internal/unique_ptr.h>
35#include <zorba/item_sequence.h>34#include <zorba/item_sequence.h>
36#include <zorba/iterator.h>35#include <zorba/iterator.h>
37#include <zorba/xquery_functions.h>36#include <zorba/properties.h>
38#include <zorba/uri_resolvers.h>
39#include <zorba/serialization_callback.h>37#include <zorba/serialization_callback.h>
40#include <zorba/audit.h>
41#include <zorba/audit_scoped.h>
42#include <zorba/store_manager.h>38#include <zorba/store_manager.h>
39#include <zorba/uri_resolvers.h>
43#include <zorba/util/fs_util.h>40#include <zorba/util/fs_util.h>
44#include <zorba/internal/unique_ptr.h>41#include <zorba/xquery_exception.h>
42#include <zorba/xquery_functions.h>
43#include <zorba/zorba.h>
44#include <zorba/zorba_exception.h>
4545
46//#define DO_AUDIT46//#define DO_AUDIT
4747
@@ -50,850 +50,464 @@
50#include <zorba/audit_scoped.h>50#include <zorba/audit_scoped.h>
51#endif51#endif
5252
53// local
54#include "timers.h"
53#include "util.h"55#include "util.h"
54#include "path_util.h"56#include "zorbacmd_props.h"
55
56// Timing utilities, including wall-clock timing
57#include <zorba/util/time.h>
5857
59// toggle this to allow configuration via a system properties file58// toggle this to allow configuration via a system properties file
60// (see src/system/properties.*)59// (see src/system/properties.*)
61#define ZORBACMD_LOAD_SYSTEM_PROPERTIES 160#define ZORBACMD_LOAD_SYSTEM_PROPERTIES 1
6261
63#if ZORBACMD_LOAD_SYSTEM_PROPERTIES62using namespace std;
64# include "system/properties.h"
65#endif
66
67//#define DO_AUDIT
68
69using namespace zorba;63using namespace zorba;
70namespace zorbatm = zorba::time;64
7165extern char const* get_help_msg();
72const char *copyright_str =66extern int parse_args( int argc, char const *argv[] );
73 "Copyright 2006-2009 The FLWOR Foundation.\n"67static void set_paths_on_sctx( StaticContext_t& );
68
69///////////////////////////////////////////////////////////////////////////////
70
71static const char copyright[] =
72 "Copyright 2006-2014 The FLWOR Foundation.\n"
74 "License: Apache License 2.0: <http://www.apache.org/licenses/LICENSE-2.0>";73 "License: Apache License 2.0: <http://www.apache.org/licenses/LICENSE-2.0>";
7574
76#ifndef ZORBA_NO_FULL_TEXT75#ifndef ZORBA_NO_FULL_TEXT
77OneToOneURIMapper theStopWordsMapper(EntityData::STOP_WORDS);76static OneToOneURIMapper stop_words_mapper( EntityData::STOP_WORDS );
78OneToOneURIMapper theThesaurusMapper(EntityData::THESAURUS);77static OneToOneURIMapper thesaurus_mapper( EntityData::THESAURUS );
79#endif78#endif /* ZORBA_NO_FULL_TEXT */
8079
8180class URIMapperSerializationCallback : public SerializationCallback {
82/*******************************************************************************81public:
8382 void addURIMapper( URIMapper* mapper ) {
84********************************************************************************/83 theURIMappers.push_back( mapper );
85class URIMapperSerializationCallback : public SerializationCallback84 }
86{85
86 URIMapper* getURIMapper( size_t i ) const {
87 return theURIMappers[i];
88 }
89
87private:90private:
88 std::vector<URIMapper*> theURIMappers;91 vector<URIMapper*> theURIMappers;
89
90public:
91 void addURIMapper(URIMapper* mapper) { theURIMappers.push_back(mapper); }
92
93 URIMapper* getURIMapper(size_t i) const { return theURIMappers[i]; }
94};92};
9593
9694URIMapperSerializationCallback serialization_callback;
97URIMapperSerializationCallback theSerializationCallback;95
9896static void print_exception( ZorbaException const &e ) {
99/*******************************************************************************97 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
10098 if ( zc_props.print_errors_as_xml_ )
101********************************************************************************/99 if ( zc_props.indent_ )
102static void print_exception( ZorbaException const &e,
103 ZorbaCMDProperties const &props ) {
104 using namespace std;
105
106 if ( props.printErrorsAsXml() )
107 if ( props.indent() )
108 cerr << ZorbaException::format_xml_indented;100 cerr << ZorbaException::format_xml_indented;
109 else101 else
110 cerr << ZorbaException::format_xml;102 cerr << ZorbaException::format_xml;
111 else103 else
112 cerr << ZorbaException::format_text;104 cerr << ZorbaException::format_text;
113
114 cerr << e << endl;105 cerr << e << endl;
115}106}
116107
117/*******************************************************************************108static void print_help() {
109 cout << "Zorba NoSQL Query Processor\n";
110 cout << "Available options:\n";
111 cout << get_help_msg();
112}
118113
119********************************************************************************/114static bool populateStaticContext( Zorba *zorba, StaticContext_t &sctx ) {
120bool populateStaticContext(115 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
121 Zorba* zorba,116 try {
122 zorba::StaticContext_t& sctx,
123 const ZorbaCMDProperties& props)
124{
125 try
126 {
127 // add the following module path to the static context (in this order)117 // add the following module path to the static context (in this order)
128 // 1. command-line properties118 // 1. command-line properties
129 // 2. environment ZORBA_MODULE_PATH119 // 2. environment ZORBA_MODULE_PATH
130 // 3. current working directory120 // 3. current working directory
131 {121 set_paths_on_sctx( sctx );
132 std::vector<String> lModulePath;122
133 PathUtil::setPathsOnContext(props, sctx);123 if ( !zc_props.boundary_space_.empty() )
134 }124 sctx->setBoundarySpacePolicy(
135125 zc_props.boundary_space_ == "preserve" ? preserve_space : strip_space
136 if (props.boundarySpace().size() != 0 )126 );
137 {127
138 sctx->setBoundarySpacePolicy(props.boundarySpace().compare("preserve") == 0 ?128 if ( !zc_props.construction_mode_.empty() )
139 preserve_space : 129 sctx->setConstructionMode(
140 strip_space);130 zc_props.boundary_space_ == "preserve" ? preserve_cons : strip_cons
141 }131 );
142132
143 if (props.constructionMode().size() != 0)133 if ( !zc_props.ordering_mode_.empty() )
144 {134 sctx->setOrderingMode(
145 sctx->setConstructionMode(props.boundarySpace().compare("preserve") == 0 ? 135 zc_props.boundary_space_ == "ordered" ? ordered : unordered
146 preserve_cons :136 );
147 strip_cons);137
148 }138 if ( !zc_props.base_uri_.empty() )
149139 sctx->setBaseURI( zc_props.base_uri_ );
150 if (props.orderingMode().size() != 0 )
151 {
152 sctx->setOrderingMode(props.boundarySpace().compare("ordered") == 0 ?
153 ordered :
154 unordered);
155 }
156
157 if (props.baseUri().size() != 0 )
158 sctx->setBaseURI( props.baseUri() );
159 }140 }
160 catch (const zorba::ZorbaException& ze) 141 catch ( ZorbaException const &ze ) {
161 {142 cerr << ze << endl;
162 std::cerr << ze << std::endl;
163 return false;143 return false;
164 }144 }
165145
166 if (props.defaultCollation().size() != 0 )146 if ( !zc_props.default_collation_.empty() ) {
167 {147 try {
168 try 148 sctx->addCollation( zc_props.default_collation_ );
169 {
170 sctx->addCollation( props.defaultCollation() );
171 }149 }
172 catch (zorba::ZorbaException const&)150 catch ( ZorbaException const& ) {
173 {151 cerr << "the given collation {" << zc_props.default_collation_
174 std::cerr << "the given collation {" << props.defaultCollation()152 << "} is not a valid collation." << endl;
175 << "} is not a valid collation." << std::endl;
176 return false;153 return false;
177 }154 }
178155 sctx->setDefaultCollation( zc_props.default_collation_ );
179 sctx->setDefaultCollation( props.defaultCollation() );
180 }156 }
181157
182 ZorbaCMDProperties::Options_t::const_iterator lIter = props.optionsBegin();158 sctx_opts::const_iterator i = zc_props.sctx_opts_.begin();
183 ZorbaCMDProperties::Options_t::const_iterator end = props.optionsEnd();159 sctx_opts::const_iterator const end = zc_props.sctx_opts_.end();
184 for (; lIter != end; ++lIter)160 for ( ; i != end; ++i ) {
185 {161 try {
186 try 162 Item name( zorba->getItemFactory()->createQName( i->clark_qname ) );
187 {163 sctx->declareOption( name, i->value );
188 Item lQName = zorba->getItemFactory()->createQName(lIter->clark_qname);
189 sctx->declareOption(lQName, lIter->value);
190 }164 }
191 catch (zorba::ZorbaException const& e)165 catch ( ZorbaException const &e) {
192 {166 cerr << "unable to set static context option with qname "
193 std::cerr << "unable to set static context option with qname "167 << i->clark_qname << ": " << e.what() << endl;
194 << lIter->clark_qname << ": " << e.what() << std::endl;
195 return false;168 return false;
196 }169 }
197 }170 }
198171
199#ifdef DO_AUDIT172#ifdef DO_AUDIT
200 zorba::audit::Provider* lAuditProvider = zorba->getAuditProvider();173 audit::Provider* lAuditProvider = zorba->getAuditProvider();
201 zorba::audit::Configuration* config = lAuditProvider->createConfiguration();174 audit::Configuration* config = lAuditProvider->createConfiguration();
202 std::vector<zorba::String> property_names;175 vector<String> property_names;
203 zorba::audit::Configuration::getPropertyNames(property_names);176 audit::Configuration::getPropertyNames(property_names);
204177
205 bool lIsStatic;178 bool lIsStatic;
206179
207 lIsStatic = zorba::audit::Configuration::180 lIsStatic = audit::Configuration::
208 enableProperty(config, property_names, "xquery/compilation/parse-duration");181 enableProperty(config, property_names, "xquery/compilation/parse-duration");
209 assert(lIsStatic);182 assert(lIsStatic);
210183
211 lIsStatic = zorba::audit::Configuration::184 lIsStatic = audit::Configuration::
212 enableProperty(config, property_names, "xquery/compilation/translation-duration");185 enableProperty(config, property_names, "xquery/compilation/translation-duration");
213 assert(lIsStatic);186 assert(lIsStatic);
214187
215 lIsStatic = zorba::audit::Configuration::188 lIsStatic = audit::Configuration::
216 enableProperty(config, property_names, "xquery/compilation/optimization-duration");189 enableProperty(config, property_names, "xquery/compilation/optimization-duration");
217 assert(lIsStatic);190 assert(lIsStatic);
218191
219 lIsStatic = zorba::audit::Configuration::192 lIsStatic = audit::Configuration::
220 enableProperty(config, property_names, "xquery/compilation/codegeneration-duration");193 enableProperty(config, property_names, "xquery/compilation/codegeneration-duration");
221 assert(lIsStatic);194 assert(lIsStatic);
222195
223 zorba::audit::Event* event = lAuditProvider->createEvent(config);196 audit::Event *event = lAuditProvider->createEvent(config);
224197
225 sctx->setAuditEvent(event);198 sctx->setAuditEvent( event );
226#endif // DO_AUDIT199#endif /* DO_AUDIT */
227200
228#ifndef ZORBA_NO_FULL_TEXT201#ifndef ZORBA_NO_FULL_TEXT
229 {202 {
230 ZorbaCMDProperties::FullText_t::const_iterator lIter = props.stopWordsBegin();203 ft_mappings::const_iterator i = zc_props.stop_words_mapping_.begin();
231 ZorbaCMDProperties::FullText_t::const_iterator end = props.stopWordsEnd();204 ft_mappings::const_iterator const end = zc_props.stop_words_mapping_.end();
232 for (; lIter != end; ++lIter) 205 for (; i != end; ++i)
233 {206 stop_words_mapper.addMapping( i->uri, i->value );
234 theStopWordsMapper.addMapping(lIter->uri, lIter->value);
235 }
236207
237 if (props.serializePlan() || props.loadPlan()) 208 if ( zc_props.serialize_plan_ || zc_props.load_plan_ )
238 {209 serialization_callback.addURIMapper( &stop_words_mapper );
239 theSerializationCallback.addURIMapper(&theStopWordsMapper);
240 }
241 else210 else
242 {211 sctx->registerURIMapper( &stop_words_mapper );
243 sctx->registerURIMapper(&theStopWordsMapper);
244 }
245 }212 }
246213
247 {214 {
248 ZorbaCMDProperties::FullText_t::const_iterator lIter = props.thesaurusBegin();215 ft_mappings::const_iterator i = zc_props.thesaurus_mapping_.begin();
249 ZorbaCMDProperties::FullText_t::const_iterator end = props.thesaurusEnd();216 ft_mappings::const_iterator const end = zc_props.thesaurus_mapping_.end();
250 for (; lIter != end; ++lIter) 217 for ( ; i != end; ++i )
251 {218 thesaurus_mapper.addMapping( i->uri, i->value );
252 theThesaurusMapper.addMapping(lIter->uri, lIter->value);
253 }
254219
255 if (props.serializePlan() || props.loadPlan())220 if ( zc_props.serialize_plan_ || zc_props.load_plan_ )
256 {221 serialization_callback.addURIMapper( &stop_words_mapper );
257 theSerializationCallback.addURIMapper(&theStopWordsMapper);
258 }
259 else222 else
260 {223 sctx->registerURIMapper( &thesaurus_mapper );
261 sctx->registerURIMapper(&theThesaurusMapper);
262 }
263 }224 }
264#endif /* ZORBA_NO_FULL_TEXT */225#endif /* ZORBA_NO_FULL_TEXT */
265226
266 return true;227 return true;
267}228}
268229
269230bool populateDynamicContext( Zorba *zorba, XmlDataManager *xmlMgr,
270/*******************************************************************************231 DynamicContext *dctx ) {
271232 ZorbaCmdProperties const &zc_props = ZorbaCmdProperties::instance();
272********************************************************************************/233
273bool populateDynamicContext(234 if ( !zc_props.ctx_item_.empty() ) {
274 Zorba* zorba,235 ifstream is( zc_props.ctx_item_.c_str() );
275 XmlDataManager* xmlMgr,236 Item doc( xmlMgr->parseXML( is ) );
276 zorba::DynamicContext* aDynamicContext,237 dctx->setContextItem( doc );
277 const ZorbaCMDProperties& props)
278{
279 if ( props.contextItem().size() != 0 )
280 {
281 std::ifstream lInStream(props.contextItem().c_str());
282 Item lDoc = xmlMgr->parseXML(lInStream);
283 aDynamicContext->setContextItem(lDoc);
284 }238 }
285239
286 ZorbaCMDProperties::ExternalVars_t::const_iterator lIter;240 external_vars::const_iterator i = zc_props.external_vars_.begin();
287 ZorbaCMDProperties::ExternalVars_t::const_iterator end = props.externalVarsEnd();241 external_vars::const_iterator const end = zc_props.external_vars_.end();
288 for (lIter = props.externalVarsBegin();242 for ( ; i != end; ++i ) {
289 lIter != end;243 try {
290 ++lIter)244 if ( i->inline_file ) {
291 {245 ifstream is( i->var_value.c_str() );
292 try246 Item doc( xmlMgr->parseXML( is ) );
293 {247 dctx->setVariable( i->var_name, doc );
294 if ((*lIter).inline_file)248 } else {
295 {249 Item item( zorba->getItemFactory()->createString( i->var_value ) );
296 std::ifstream lInStream((*lIter).var_value.c_str());250 dctx->setVariable( i->var_name, item );
297 Item lDoc = xmlMgr->parseXML(lInStream);
298 aDynamicContext->setVariable((*lIter).var_name, lDoc);
299 }
300 else
301 {
302 zorba::Item lItem = zorba->getItemFactory()->createString((*lIter).var_value);
303 aDynamicContext->setVariable((*lIter).var_name, lItem);
304 }251 }
305 }252 }
306 catch (...)253 catch ( ... ) {
307 {
308 // Let normal exception handling display the error message; here we254 // Let normal exception handling display the error message; here we
309 // just want to tell the user what variable binding caused the problem255 // just want to tell the user what variable binding caused the problem
310 std::cerr << "While binding external variable $"256 cerr << "While binding external variable $" << i->var_name << ": ";
311 << lIter->var_name << ": ";
312 throw;257 throw;
313 }258 }
314 }259 }
315 return true;260 return true;
316}261}
317262
318263static void set_serializer_opts( Zorba_SerializerOptions_t &ser_opts ) {
319/*******************************************************************************264 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
320265
321********************************************************************************/266 if ( zc_props.indent_ )
322bool createSerializerOptions(267 ser_opts.indent = ZORBA_INDENT_YES;
323 Zorba_SerializerOptions_t& lSerOptions,268
324 const ZorbaCMDProperties& props)269 if ( zc_props.omit_xml_declaration_ )
325{270 ser_opts.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES;
326 if ( props.indent() )271
327 lSerOptions.indent = ZORBA_INDENT_YES;272 if ( zc_props.byte_order_mark_ )
328273 ser_opts.byte_order_mark = ZORBA_BYTE_ORDER_MARK_YES;
329 if ( props.omitXmlDeclaration() )274
330 lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES;275 if ( zc_props.serialize_html_ )
331276 ser_opts.ser_method = ZORBA_SERIALIZATION_METHOD_HTML;
332 if ( props.byteOrderMark() )277 else if ( zc_props.serialize_text_ )
333 lSerOptions.byte_order_mark = ZORBA_BYTE_ORDER_MARK_YES;278 ser_opts.ser_method = ZORBA_SERIALIZATION_METHOD_TEXT;
334
335 if ( props.serializeHtml() )
336 lSerOptions.ser_method = ZORBA_SERIALIZATION_METHOD_HTML;
337 else if ( props.serializeText() )
338 lSerOptions.ser_method = ZORBA_SERIALIZATION_METHOD_TEXT;
339
340 return true;
341}279}
342280
343281
344/*******************************************************************************282/******************************************************************************
345 Fullfills the command-line "as-file" (-f) switch, or if not requested, infers283 Fullfills the command-line "as-file" (-f) switch, or if not requested, infers
346 -f for file:// queries. Returns an URI or the empty string.284 -f for file:// queries. Returns an URI or the empty string.
347********************************************************************************/285 ******************************************************************************/
348std::string parseFileURI(bool asPath, const std::string &str)
349{
350 if (asPath)
351 return str;
352286
353 // otherwise, the user still might have meant a file287static string parse_file_uri( string const &uri ) {
354#ifdef WIN32288#ifdef WIN32
355 // file:///c:/ returns c:<backslash>289 // file:///c:/ returns c:<backslash>
356 // file://localhost returns \\localhost290 // file://localhost returns \\localhost
357 // BUG: it seems that <a>/x returns <a>\x291 // BUG: it seems that <a>/x returns <a>\x
358 static const char *file3 = "file:///";292 static const char *file3 = "file:///";
359 static const char *file2 = "file://";293 static const char *file2 = "file://";
360 std::string fpath;294 string fpath;
361 if(str.compare(0, strlen(file3), file3) == 0) {295 if ( uri.compare( 0, strlen( file3 ), file3 ) == 0 ) {
362 fpath = str.substr(strlen(file3));296 fpath = uri.substr( strlen( file3 ) );
363 } else if(str.compare(0, strlen(file2), file2) == 0) {297 } else if ( uri.compare( 0, strlen( file2 ), file2 ) == 0 ) {
364 fpath = fs::dir_separator;298 fpath = fs::dir_separator;
365 fpath += str.substr(strlen(file2));299 fpath += uri.substr( strlen( file2 ) );
366 }300 }
367 // replace all slash with backslash301 // replace all slash with backslash
368 std::string::size_type off=0;302 string::size_type off=0;
369 while ((off=fpath.find('/', off)) != std::string::npos)303 while ( (off = fpath.find( '/', off )) != string::npos )
370 fpath.replace(off, 1, 1, fs::dir_separator);304 fpath.replace( off, 1, 1, fs::dir_separator );
371 return fpath;305 return fpath;
372306
373#else // for UNIX307#else /* for UNIX */
374308 static const char pfx[] = "file://";
375 static const char *pfx = "file://";309 if ( uri.compare( 0, 7, pfx ) == 0 )
376 static unsigned plen = strlen (pfx);310 return uri.substr( 7 );
377 if (str.compare (0, plen, pfx) == 0)
378 return str.substr (plen);
379 else311 else
380 return "";312 return "";
381#endif313#endif /* WIN32 */
382}314}
383315
384316static void remove_output_file() {
385//
386// Timing utilities and class
387//
388
389#define DECLARE_TIMER(kind) \
390 zorbatm::walltime start##kind##Walltime; \
391 zorbatm::walltime stop##kind##Walltime; \
392 zorbatm::cputime start##kind##Cputime; \
393 zorbatm::cputime stop##kind##Cputime; \
394 double elapsed##kind##Walltime; \
395 double elapsed##kind##Cputime
396
397#define START_TIMER(kind) \
398 zorbatm::get_current_walltime(start##kind##Walltime); \
399 zorbatm::get_current_cputime(start##kind##Cputime);
400
401#define STOP_TIMER(kind) \
402 zorbatm::get_current_walltime(stop##kind##Walltime); \
403 elapsed##kind##Walltime += zorbatm::get_walltime_elapsed(start##kind##Walltime, \
404 stop##kind##Walltime); \
405 \
406 zorbatm::get_current_cputime(stop##kind##Cputime); \
407 elapsed##kind##Cputime += zorbatm::get_cputime_elapsed(start##kind##Cputime, \
408 stop##kind##Cputime);
409
410
411
412struct TimingInfo
413{
414 typedef enum
415 {
416 INIT_TIMER,
417 DEINIT_TIMER,
418 COMP_TIMER,
419 EXEC_TIMER,
420 UNLOAD_TIMER,
421 PLAN_SAVE_TIMER,
422 PLAN_LOAD_TIMER,
423 TOTAL_TIMER
424 } TimerKind;
425
426 unsigned long numExecs;
427
428 DECLARE_TIMER(Init);
429 DECLARE_TIMER(Deinit);
430 DECLARE_TIMER(Comp);
431 DECLARE_TIMER(Exec);
432 DECLARE_TIMER(Load);
433 DECLARE_TIMER(Unload);
434 DECLARE_TIMER(PlanSave);
435 DECLARE_TIMER(PlanLoad);
436 DECLARE_TIMER(Total);
437
438 TimingInfo(unsigned long num)
439 :
440 numExecs(num),
441 elapsedInitWalltime(0),
442 elapsedInitCputime(0),
443 elapsedDeinitWalltime(0),
444 elapsedDeinitCputime(0),
445 elapsedCompWalltime(0),
446 elapsedCompCputime(0),
447 elapsedExecWalltime(0),
448 elapsedExecCputime(0),
449 elapsedLoadWalltime(0),
450 elapsedLoadCputime(0),
451 elapsedUnloadWalltime(0),
452 elapsedUnloadCputime(0),
453
454 elapsedPlanSaveWalltime(0),
455 elapsedPlanSaveCputime(0),
456
457 elapsedPlanLoadWalltime(0),
458 elapsedPlanLoadCputime(0),
459
460 elapsedTotalWalltime(0),
461 elapsedTotalCputime(0)
462 {
463 }
464
465 void startTimer(TimerKind kind, unsigned long iteration);
466 void stopTimer(TimerKind kind, unsigned long iteration);
467
468 std::ostream& print(std::ostream& os, bool);
469};
470
471
472void
473TimingInfo::startTimer(TimerKind kind, unsigned long iteration)
474{
475 if (iteration == 0 && numExecs > 1)
476 return;
477
478 switch (kind)
479 {
480 case INIT_TIMER:
481 START_TIMER(Init);
482 break;
483
484 case DEINIT_TIMER:
485 START_TIMER(Deinit);
486 break;
487
488 case TOTAL_TIMER:
489 START_TIMER(Total);
490 break;
491
492 case COMP_TIMER:
493 START_TIMER(Comp);
494 break;
495
496 case EXEC_TIMER:
497 START_TIMER(Exec);
498 break;
499
500 case UNLOAD_TIMER:
501 START_TIMER(Unload);
502 break;
503
504 case PLAN_SAVE_TIMER:
505 START_TIMER(PlanSave);
506 break;
507
508 case PLAN_LOAD_TIMER:
509 START_TIMER(PlanLoad);
510 break;
511 }
512}
513
514
515void
516TimingInfo::stopTimer(TimerKind kind, unsigned long iteration)
517{
518 if (iteration == 0 && numExecs > 1)
519 return;
520
521 switch (kind)
522 {
523 case INIT_TIMER:
524 {
525 STOP_TIMER(Init);
526 break;
527 }
528 case DEINIT_TIMER:
529 {
530 STOP_TIMER(Deinit);
531 break;
532 }
533 case TOTAL_TIMER:
534 {
535 STOP_TIMER(Total);
536 break;
537 }
538 case COMP_TIMER:
539 {
540 STOP_TIMER(Comp);
541 break;
542 }
543 case EXEC_TIMER:
544 {
545 STOP_TIMER(Exec);
546 break;
547 }
548 case UNLOAD_TIMER:
549 {
550 STOP_TIMER(Unload);
551 break;
552 }
553 case PLAN_SAVE_TIMER:
554 {
555 STOP_TIMER(PlanSave);
556 break;
557 }
558 case PLAN_LOAD_TIMER:
559 {
560 STOP_TIMER(PlanLoad);
561 break;
562 }
563 }
564}
565
566
567std::ostream&
568TimingInfo::print(std::ostream& os, bool serializePlan)
569{
570 os.precision(3);
571 os.setf(std::ios::fixed);
572
573 os << "\nNumber of executions = " << numExecs << std::endl;
574
575 unsigned long timeDiv = numExecs == 1 ? 1 : (numExecs - 1);
576 double cWalltime = elapsedCompWalltime / timeDiv;
577 double eWalltime = elapsedExecWalltime / timeDiv;
578 double lWalltime = elapsedLoadWalltime / timeDiv;
579 double uWalltime = elapsedUnloadWalltime / timeDiv;
580 double psWalltime = elapsedPlanSaveWalltime / timeDiv;
581 double plWalltime = elapsedPlanLoadWalltime / timeDiv;
582 double tWalltime = elapsedTotalWalltime / timeDiv;
583
584 double cCputime = elapsedCompCputime / timeDiv;
585 double eCputime = elapsedExecCputime / timeDiv;
586 double lCputime = elapsedLoadCputime / timeDiv;
587 double uCputime = elapsedUnloadCputime / timeDiv;
588 double psCputime = elapsedPlanSaveCputime / timeDiv;
589 double plCputime = elapsedPlanLoadCputime / timeDiv;
590 double tCputime = elapsedTotalCputime / timeDiv;
591
592 os << "Engine Startup Time : " << elapsedInitWalltime
593 << " (user: " << elapsedInitCputime << ")"
594 << " milliseconds" << std::endl;
595
596 os << "Average Compilation Time: " << cWalltime
597 << " (user: " << cCputime << ")"
598 << " milliseconds" << std::endl;
599
600 if (serializePlan)
601 {
602 os << "Average Plan Saving Time: " << psWalltime
603 << " (user: " << psCputime << ")"
604 << " milliseconds" << std::endl;
605
606 os << "Average Plan Loading Time: " << plWalltime
607 << " (user: " << plCputime << ")"
608 << " milliseconds" << std::endl;
609 }
610
611 os << "Average Execution Time : " << eWalltime - lWalltime
612 << " (user: " << eCputime - lCputime << ")"
613 << " milliseconds" << std::endl;
614
615 os << "Average Loading Time : " << lWalltime
616 << " (user: " << lCputime << ")"
617 << " milliseconds" << std::endl;
618
619 os << "Average Unloading Time : " << uWalltime
620 << " (user: " << uCputime << ")"
621 << " milliseconds" << std::endl;
622
623 os << "Average Total Time : " << tWalltime
624 << " (user: " << tCputime << ")"
625 << " milliseconds" << std::endl;
626
627 return os;
628}
629
630
631void
632removeOutputFileIfNeeded(const ZorbaCMDProperties& lProperties)
633{
634#ifdef ZORBA_WITH_FILE_ACCESS317#ifdef ZORBA_WITH_FILE_ACCESS
635 if ( !lProperties.outputFile().empty() )318 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
636 fs::remove( lProperties.outputFile(), true );319 if ( !zc_props.output_file_.empty() )
320 fs::remove( zc_props.output_file_, true );
637#endif /* ZORBA_WITH_FILE_ACCESS */321#endif /* ZORBA_WITH_FILE_ACCESS */
638}322}
639323
640324static int compileAndExecute( Zorba *zorba, XmlDataManager *xmlDataMgr,
641int325 StaticContext_t &sctx,
642compileAndExecute(326 string const &qfilepath,
643 zorba::Zorba* zorbaInstance,327 istream &qstream,
644 zorba::XmlDataManager* xmlDataMgr,328 ostream &outputStream,
645 const ZorbaCMDProperties& properties,329 Timers &timers ) {
646 zorba::StaticContext_t& staticContext,330 Properties const &z_props = Properties::instance();
647 const std::string& qfilepath,331 ZorbaCmdProperties const &zc_props = ZorbaCmdProperties::instance();
648 std::istream& qfile,332
649 std::ostream& outputStream,333 unsigned long lNumExecutions = zc_props.multiple_;
650 TimingInfo& timing)334 ostringstream lOut;
651{335 Zorba_CompilerHints hints;
652 unsigned long lNumExecutions = properties.multiple();336
653 bool doTiming = properties.timing();337 unique_ptr<fstream> planFile;
654 bool serializePlan = properties.serializePlan();338 fstream *planFilep = NULL;
655 bool savePlan = properties.savePlan();339
656 bool loadPlan = properties.loadPlan();340 if ( zc_props.jsoniq_ || fs::extension( qfilepath ) == "jq" )
657 std::ostringstream lOut;341 sctx->setJSONiqVersion( jsoniq_version_1_0 );
658 Zorba_CompilerHints lHints;342
659343 if ( zc_props.serialize_plan_ ) {
660 std::unique_ptr<std::fstream> planFile;344 if ( zc_props.load_plan_ || zc_props.save_plan_ ) {
661 std::fstream* planFilep = NULL;345 cerr << "The --serialize-plan option cannot be used together with the --compile-plan or --execute-plan options" << endl;
662346 exit( 1 );
663 if (qfilepath.rfind(".jq") == qfilepath.size() - 3)
664 {
665 staticContext->setJSONiqVersion(zorba::jsoniq_version_1_0);
666 }
667
668 if (serializePlan)
669 {
670 if (savePlan || loadPlan)
671 {
672 std::cerr << "The --serialize-plan option cannot be used together with the --compile-plan or --execute-plan options" << std::endl;
673 exit(1);
674 }347 }
675348
676 std::string planFilePath = qfilepath;349 string planFilePath = qfilepath;
677 planFilePath += ".plan";350 planFilePath += ".plan";
678 planFile.reset(new std::fstream(planFilePath.c_str(), 351 planFile.reset(
679 std::fstream::in | 352 new fstream(
680 std::fstream::out |353 planFilePath.c_str(), ios::in | ios::out | ios::trunc | ios::binary
681 std::fstream::trunc |354 )
682 std::fstream::binary));355 );
683 planFilep = planFile.get();356 planFilep = planFile.get();
684 assert(planFilep->good());357 assert(planFilep->good());
685 }358 }
686359
687 if (savePlan && loadPlan)360 if ( zc_props.save_plan_ && zc_props.load_plan_ ) {
688 {361 cerr << "The --compile-plan and --execute-plan options cannot be used together" << endl;
689 std::cerr << "The --compile-plan and --execute-plan options cannot be used together" << std::endl;362 exit( 1 );
690 exit(1);
691 }363 }
692364
693 // default is O1 in the Zorba_CompilerHints constructor365 // default is O1 in the Zorba_CompilerHints constructor
694 if (properties.optimizationLevel() == "O0") 366 switch ( z_props.getOptimizationLevel() ) {
695 {367 case 0: hints.opt_level = ZORBA_OPT_LEVEL_O0; break;
696 lHints.opt_level = ZORBA_OPT_LEVEL_O0;368 case 2: hints.opt_level = ZORBA_OPT_LEVEL_O2; break;
697 }369 }
698 else if (properties.optimizationLevel() == "O2") 370
699 {371 hints.for_serialization_only = zc_props.serialize_only_query_;
700 lHints.opt_level = ZORBA_OPT_LEVEL_O2;372 hints.lib_module = zc_props.lib_module_;
701 }373
702374 Zorba_SerializerOptions ser_opts;
703 lHints.for_serialization_only = true;
704
705#if ZORBACMD_LOAD_SYSTEM_PROPERTIES
706 if (Properties::instance()->serializeOnlyQuery() == 0)
707 {
708 lHints.for_serialization_only = false;
709 }
710#endif
711
712 // default is false
713 if (properties.libModule())
714 {
715 lHints.lib_module = true;
716 }
717
718 Zorba_SerializerOptions lSerOptions;
719 try {375 try {
720 lSerOptions.set( properties.getSerializerParameters() );376 ser_opts.set( zc_props.serialization_params_ );
721 }377 }
722 catch ( zorba::ZorbaException const &e ) {378 catch ( ZorbaException const &e ) {
723 std::cerr << e << std::endl;379 cerr << e << endl;
724 return 11;380 return 11;
725 }381 }
726 createSerializerOptions(lSerOptions, properties);382 set_serializer_opts( ser_opts );
727383
728 zorba::XQuery_t query;384 XQuery_t query;
729 DiagnosticHandler diagnosticHandler;385 DiagnosticHandler diagnosticHandler;
730386
731 for (unsigned long i = 0; i < lNumExecutions; ++i)387 for ( unsigned long exec = 0; exec < lNumExecutions; ++exec ) {
732 {388 if ( zc_props.timing_ )
733 // start the total timer389 timers.startTimer( Timers::total, exec );
734 if (doTiming)390
735 timing.startTimer(TimingInfo::TOTAL_TIMER, i);
736
737 //391 //
738 // Compile the query392 // Compile the query
739 // Compilation is done only once, unless timing is needed393 // Compilation is done only once, unless timing is needed
740 //394 //
741 if (doTiming || i == 0)395 if ( zc_props.timing_ || exec == 0 ) {
742 {
743 // go back to the beginning of the stream396 // go back to the beginning of the stream
744 qfile.clear();397 qstream.clear();
745 qfile.seekg(0);398 qstream.seekg( 0 );
746 assert (qfile.tellg() >= 0);399 assert( qstream.tellg() >= 0 );
747400
748 try401 try {
749 {402 if ( zc_props.timing_ )
750 // start the compilation timer403 timers.startTimer( Timers::comp, exec );
751 if (doTiming)
752 timing.startTimer(TimingInfo::COMP_TIMER, i);
753404
754 // Create and compile the query405 // Create and compile the query
755 query = zorbaInstance->createQuery();406 query = zorba->createQuery();
756 query->registerDiagnosticHandler(&diagnosticHandler);407 query->registerDiagnosticHandler( &diagnosticHandler );
757 query->setFileName(qfilepath);408 query->setFileName( qfilepath );
758409
759 if (loadPlan) 410 if ( zc_props.load_plan_ ) {
760 {411 query->loadExecutionPlan( qstream, &serialization_callback );
761 query->loadExecutionPlan(qfile, &theSerializationCallback);412 if ( zc_props.timing_ )
762413 timers.stopTimer( Timers::comp, exec );
763 // stop the compilation timer414 } else {
764 if (doTiming)415 query->compile( qstream, sctx, hints );
765 timing.stopTimer(TimingInfo::COMP_TIMER, i);416
766 }417 if ( zc_props.timing_ )
767 else418 timers.stopTimer( Timers::comp, exec );
768 {
769 query->compile(qfile, staticContext, lHints);
770
771 // stop the compilation timer
772 if (doTiming)
773 timing.stopTimer(TimingInfo::COMP_TIMER, i);
774419
775 // Serialize the execution plan, if requested420 // Serialize the execution plan, if requested
776 if (serializePlan) 421 if ( zc_props.serialize_plan_ ) {
777 {
778 planFilep->clear();422 planFilep->clear();
779 planFilep->seekp(0);423 planFilep->seekp( 0 );
780424
781 // start the plan-save timer425 if ( zc_props.timing_ )
782 if (doTiming)426 timers.startTimer( Timers::plan_save, exec );
783 timing.startTimer(TimingInfo::PLAN_SAVE_TIMER, i);427 query->saveExecutionPlan( *planFilep );
784428 if ( zc_props.timing_ )
785 query->saveExecutionPlan(*planFilep);429 timers.stopTimer( Timers::plan_save, exec );
786
787 // stop the plan-save timer
788 if (doTiming)
789 timing.stopTimer(TimingInfo::PLAN_SAVE_TIMER, i);
790
791 planFilep->flush();430 planFilep->flush();
792 }431 }
793 }432 }
794 }433 }
795 catch (zorba::XQueryException const& qe)434 catch ( XQueryException const &qe ) {
796 {435 print_exception( qe );
797 print_exception( qe, properties );
798 return 11;436 return 11;
799 }437 }
800 catch (zorba::ZorbaException const& ze)438 catch ( ZorbaException const &ze ) {
801 {439 cerr << ze << endl;
802 std::cerr << ze << std::endl;
803 return 12;440 return 12;
804 }441 }
805 } // if (doTiming || i == 0)442 } // if (zc_props.timing_ || exec == 0)
806443
807 //444 //
808 // Run the query, unless compileOnly has been requested.445 // Run the query, unless compile-only has been requested.
809 //446 //
810 if ( ! properties.compileOnly() && ! properties.libModule() )447 if ( !zc_props.compile_only_ && !zc_props.lib_module_ ) {
811 {448 try {
812 try
813 {
814 // load the execution plan, if requested449 // load the execution plan, if requested
815 if (serializePlan) 450 if ( zc_props.serialize_plan_ ) {
816 {451 planFilep->seekg( 0 );
817 planFilep->seekg(0);452 assert( planFilep->good() );
818 assert(planFilep->good());453
819 454 if ( zc_props.timing_ )
820 // start the plan-load timer455 timers.startTimer( Timers::plan_load, exec );
821 if (doTiming)456
822 timing.startTimer(TimingInfo::PLAN_LOAD_TIMER, i);457 query = zorba->createQuery();
823458 query->loadExecutionPlan( *planFilep, &serialization_callback );
824 query = zorbaInstance->createQuery();459
825 query->loadExecutionPlan(*planFilep, &theSerializationCallback);460 if ( zc_props.timing_ )
826461 timers.stopTimer( Timers::plan_load, exec );
827 // stop the plan-load timer
828 if (doTiming)
829 timing.stopTimer(TimingInfo::PLAN_LOAD_TIMER, i);
830 }462 }
831463
832 // start the execution timer464 if ( zc_props.timing_ )
833 if (doTiming)465 timers.startTimer( Timers::exec, exec );
834 timing.startTimer(TimingInfo::EXEC_TIMER, i);
835466
836 // Populate the dynamic context467 // Populate the dynamic context
837 zorba::DynamicContext* lDynamicContext = query->getDynamicContext();468 try {
838 try469 DynamicContext *const dctx = query->getDynamicContext();
839 {470 if ( !populateDynamicContext( zorba, xmlDataMgr, dctx ) ) {
840 if ( ! populateDynamicContext(zorbaInstance,471 print_help();
841 xmlDataMgr,
842 lDynamicContext,
843 properties) )
844 {
845 properties.printHelp(std::cout);
846 return 21;472 return 21;
847 }473 }
848 }474 }
849 catch (zorba::XQueryException const& qe)475 catch ( XQueryException const &qe ) {
850 {476 print_exception( qe );
851 print_exception( qe, properties );
852 return 22;477 return 22;
853 }478 }
854 catch (zorba::ZorbaException const& ze)479 catch ( ZorbaException const &ze ) {
855 {480 cerr << ze << endl;
856 std::cerr << ze << std::endl;
857 return 23;481 return 23;
858 }482 }
859483
860 // run the query484 // run the query
861 if (properties.noSerializer())485 if ( zc_props.no_serializer_ )
862 {
863 query->executeSAX();486 query->executeSAX();
864 }487 else if ( zc_props.save_plan_ )
865 else if (savePlan)488 query->saveExecutionPlan( outputStream );
866 {
867 query->saveExecutionPlan(outputStream);
868 }
869 else489 else
870 {490 query->execute( outputStream, &ser_opts );
871 query->execute(outputStream, &lSerOptions);491
872 }492 if ( zc_props.trailing_nl_ )
873493 outputStream << endl;
874 if (properties.trailingNl()) 494
875 outputStream << std::endl;
876
877 query->close();495 query->close();
878496
879 // stop the execution timer497 if ( zc_props.timing_ )
880 if (doTiming)498 timers.stopTimer( Timers::exec, exec );
881 timing.stopTimer(TimingInfo::EXEC_TIMER, i);
882499
883 if (i > 0 || lNumExecutions == 1) 500 if ( exec > 0 || lNumExecutions == 1 ) {
884 {501 timers.elapsed_load_walltime += query->getDocLoadingTime();
885 timing.elapsedLoadWalltime += query->getDocLoadingTime();502 timers.elapsed_load_cputime += query->getDocLoadingUserTime();
886 timing.elapsedLoadCputime += query->getDocLoadingUserTime();
887 }503 }
888 }504 }
889 catch (zorba::XQueryException const& qe)505 catch ( XQueryException const &qe ) {
890 {506 print_exception( qe );
891 print_exception( qe, properties );
892 return 31;507 return 31;
893 }508 }
894 catch (zorba::ZorbaException const& ze)509 catch ( ZorbaException const &ze ) {
895 {510 cerr << ze << endl;
896 std::cerr << ze << std::endl;
897 return 32;511 return 32;
898 }512 }
899 }513 }
@@ -901,423 +515,374 @@
901 //515 //
902 // Delete all loaded docs from the store, if timing has been requested516 // Delete all loaded docs from the store, if timing has been requested
903 //517 //
904 if (doTiming)518 if ( zc_props.timing_ ) {
905 {519 timers.startTimer( Timers::unload, exec );
906 timing.startTimer(TimingInfo::UNLOAD_TIMER, i);
907520
908 DocumentManager* docMgr = xmlDataMgr->getDocumentManager();521 DocumentManager *const docMgr = xmlDataMgr->getDocumentManager();
909 ItemSequence_t docsSeq = docMgr->availableDocuments();522 ItemSequence_t docsSeq = docMgr->availableDocuments();
910 Iterator_t lIter = docsSeq->getIterator();523 Iterator_t i( docsSeq->getIterator() );
911 lIter->open();524 i->open();
912525
913 Item uri;526 Item uri;
914 std::vector<Item> docURIs;527 vector<Item> docURIs;
915 while (lIter->next(uri)) 528 while ( i->next( uri ) )
916 {529 docURIs.push_back( uri );
917 docURIs.push_back(uri);530 i->close();
918 }531
919 lIter->close();532 for ( vector<Item>::const_iterator
920533 i = docURIs.begin(); i != docURIs.end(); ++i ) {
921 size_t numDocs = docURIs.size();534 docMgr->remove( i->getStringValue() );
922535 }
923 for (size_t k = 0; k < numDocs; ++k)536
924 {537 timers.stopTimer( Timers::unload, exec );
925 docMgr->remove(docURIs[k].getStringValue());
926 }
927
928 timing.stopTimer(TimingInfo::UNLOAD_TIMER, i);
929 }538 }
930539
931 // stop the total timer540 if ( zc_props.timing_ )
932 if (doTiming)541 timers.stopTimer( Timers::total, exec );
933 timing.stopTimer(TimingInfo::TOTAL_TIMER, i);
934542
935#ifdef DO_AUDIT543#ifdef DO_AUDIT
936 audit::Event* event = staticContext->getAuditEvent(); 544 cerr << *sctx->getAuditEvent() << endl;
937 std::cerr << *event << std::endl;545#endif /* DO_AUDIT */
938#endif
939 } // for each execution546 } // for each execution
940547
941 return 0;548 return 0;
942}549}
943550
944/////////////////////////////////////////////////////////////////////////////////551static void set_paths_on_sctx( StaticContext_t &sctx ) {
945// //552 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
946// Main //553 vector<String> paths;
947// //554
948/////////////////////////////////////////////////////////////////////////////////555 // Compute the current working directory to append to all paths.
556 string const cwd( fs::curdir() );
557
558 // setModulePaths() *overwrites* the URI path and lib path, so there's no
559 // sense in calling both. So if --module-path exists, just use it.
560
561 if ( !zc_props.module_path_.empty() ) {
562 tokenize( zc_props.module_path_, fs::path_separator, &paths );
563 paths.push_back( cwd );
564 sctx->setModulePaths( paths );
565 } else {
566 // Compute and set URI path
567 tokenize( zc_props.uri_path_, fs::path_separator, &paths );
568 paths.push_back( cwd );
569 sctx->setURIPath( paths );
570 paths.clear();
571
572 // Compute and set lib path
573 tokenize( zc_props.lib_path_, fs::path_separator, &paths );
574 paths.push_back( cwd );
575 sctx->setLibPath( paths );
576 }
577}
578
579///////////////////////////////////////////////////////////////////////////////
580// //
581// Main //
582// //
583///////////////////////////////////////////////////////////////////////////////
949584
950#ifndef _WIN32_WCE585#ifndef _WIN32_WCE
951int586int main( int argc, char const *argv[] ) {
952main(int argc, char* argv[])
953#else587#else
954int588int _tmain( int argc, _TCHAR const *argv[] ) {
955_tmain(int argc, _TCHAR* argv[])589#endif
956#endif590 int const optind = parse_args( argc, argv );
957{591 argc -= optind;
958#if ZORBACMD_LOAD_SYSTEM_PROPERTIES592 argv += optind;
959 // only configurable via a config file or environment vars593
960 zorba::Properties::load(0, NULL);594 Properties const &z_props = Properties::instance();
961#endif595 ZorbaCmdProperties const &zc_props = ZorbaCmdProperties::instance();
962596
963 // parse the command line and/or the properties file597 Timers timers( zc_props.multiple_ );
964 ZorbaCMDProperties properties;598
965 if (!properties.loadProperties(argc, argv))
966 {
967 return 1;
968 }
969
970 TimingInfo engineTiming(properties.multiple());
971
972 bool doTiming = properties.timing();
973 bool debug = false;
974#ifdef ZORBA_WITH_DEBUGGER599#ifdef ZORBA_WITH_DEBUGGER
975 debug = (properties.debug());600 bool const debug = zc_props.debug_;
601#else
602 bool const debug = false;
976#endif603#endif
977604
978 // libModule assumes compileOnly even if compileOnly is false605 // libModule assumes compile-only even if compile-only is false
979 bool compileOnly = (properties.compileOnly() || properties.libModule() );606 bool const compile_only = zc_props.compile_only_ || zc_props.lib_module_;
980607
981 // write to file or standard out608 // write to file or standard out
982 std::unique_ptr<std::ostream> 609 unique_ptr<ostream> out_stream_ptr(
983 lFileStream(610#ifdef ZORBA_WITH_FILE_ACCESS
984 #ifdef ZORBA_WITH_FILE_ACCESS611 !zc_props.output_file_.empty() ?
985 properties.outputFile().size() > 0 ?612 new ofstream( zc_props.output_file_.c_str() ) : 0
986 new std::ofstream(properties.outputFile().c_str()) : 0613#else /* ZORBA_WITH_FILE_ACCESS */
987 #else /* ZORBA_WITH_FILE_ACCESS */614 0
988 0615#endif /* ZORBA_WITH_FILE_ACCESS */
989 #endif /* ZORBA_WITH_FILE_ACCESS */616 );
990 );
991617
992 std::ostream* lOutputStream = lFileStream.get();618 ostream *out_stream = out_stream_ptr.get();
993 if ( lOutputStream == 0 )619 if ( !out_stream )
994 {620 out_stream = &cout;
995 lOutputStream = &std::cout;
996 }
997#ifdef ZORBA_WITH_FILE_ACCESS621#ifdef ZORBA_WITH_FILE_ACCESS
998 else if ( !lOutputStream->good() )622 else if ( !out_stream->good() ) {
999 {623 cerr << "could not write to output file {" << zc_props.output_file_
1000 std::cerr << "could not write to output file {" << properties.outputFile()624 << '}' << endl;
1001 << "}" << std::endl;
1002 return 2;625 return 2;
1003 }626 }
1004#endif /* ZORBA_WITH_FILE_ACCESS */627#endif /* ZORBA_WITH_FILE_ACCESS */
1005628
1006 if (properties.queriesOrFilesBegin() == properties.queriesOrFilesEnd())629 if ( zc_props.queries_or_files_.empty() ) {
1007 {630 cerr << "no queries submitted." << endl;
1008 std::cerr << "no queries submitted." << std::endl;631 print_help();
1009 properties.printHelp(std::cout);
1010 return 3;632 return 3;
1011 }633 }
1012634
1013 // Add command line --classpath option in front of config/env CLASSPATH
1014 Properties* globaproperties = Properties::instance();
1015 std::string cmdJvmClassPath;
1016 properties.getJVMClassPath(cmdJvmClassPath);
1017 std::string configJvmClassPath;
1018 globaproperties->getJVMClassPath(configJvmClassPath);
1019 globaproperties->setJVMClassPath(cmdJvmClassPath +
1020 fs::path_separator + configJvmClassPath);
1021
1022 // Start the engine635 // Start the engine
1023636
1024 engineTiming.startTimer(TimingInfo::INIT_TIMER, 2);637 timers.startTimer( Timers::init, 2 );
1025638
1026 void* store = zorba::StoreManager::getStore();639 void *const store = StoreManager::getStore();
1027640 Zorba *const zorba = Zorba::getInstance( store );
1028 zorba::Zorba* lZorbaInstance = zorba::Zorba::getInstance(store);641
1029642 XmlDataManager_t xmlDataMgr = zorba->getXmlDataManager();
1030 zorba::XmlDataManager_t xmlDataMgr = lZorbaInstance->getXmlDataManager();
1031643
1032#ifdef DO_AUDIT644#ifdef DO_AUDIT
1033 zorba::audit::Provider* lAuditProvider = lZorbaInstance->getAuditProvider();645 audit::Provider* lAuditProvider = zorba->getAuditProvider();
1034646
1035 zorba::audit::Configuration* config = lAuditProvider->createConfiguration();647 audit::Configuration* config = lAuditProvider->createConfiguration();
1036648
1037 std::vector<zorba::String> property_names;649 vector<String> property_names;
1038 zorba::audit::Configuration::getPropertyNames(property_names);650 audit::Configuration::getPropertyNames(property_names);
1039651
1040 zorba::audit::Configuration::652 audit::Configuration::
1041 enableProperty(config, property_names, "xquery/compilation/parse-duration");653 enableProperty(config, property_names, "xquery/compilation/parse-duration");
1042654
1043 zorba::audit::Configuration::655 audit::Configuration::
1044 enableProperty(config, property_names, "xquery/compilation/translation-duration");656 enableProperty(config, property_names, "xquery/compilation/translation-duration");
1045657
1046 zorba::audit::Configuration::658 audit::Configuration::
1047 enableProperty(config, property_names, "xquery/compilation/optimization-duration");659 enableProperty(config, property_names, "xquery/compilation/optimization-duration");
1048660
1049 zorba::audit::Configuration::661 audit::Configuration::
1050 enableProperty(config, property_names, "xquery/compilation/codegeneration-duration");662 enableProperty(config, property_names, "xquery/compilation/codegeneration-duration");
1051#endif663#endif
1052664
1053 {665 {
1054 engineTiming.stopTimer(TimingInfo::INIT_TIMER, 2);666 timers.stopTimer( Timers::init, 2 );
1055667
1056 // For each query ...668 // For each query ...
1057669
1058 int queryNo;670 int query_no;
1059 ZorbaCMDProperties::QueriesOrFiles_t::const_iterator lIter;671 vector<string>::const_iterator i;
1060 for (queryNo = 1, lIter = properties.queriesOrFilesBegin();672 for ( query_no = 1, i = zc_props.queries_or_files_.begin();
1061 lIter != properties.queriesOrFilesEnd();673 i != zc_props.queries_or_files_.end(); ++query_no, ++i ) {
1062 ++queryNo, ++lIter)
1063 {
1064 //674 //
1065 // Read the query (either from a file or given as parameter)675 // Read the query (either from a file or given as parameter)
1066 //676 //
1067 std::string fURI = *lIter;677 string const uri( *i );
1068 std::string fname = parseFileURI (properties.asFiles (), fURI);678 string const fname( zc_props.as_files_ ? uri : parse_file_uri( uri ) );
1069 std::string path( fname );679 string path( fname );
1070 bool asFile = !fname.empty();680 bool const as_file = !fname.empty();
1071 std::unique_ptr<std::istream> qfile;681 unique_ptr<istream> qstream;
1072682
1073 if (asFile)683 if ( as_file ) {
1074 {
1075 fs::make_absolute( &path );684 fs::make_absolute( &path );
1076 qfile.reset( new std::ifstream( path.c_str() ) );685 qstream.reset( new ifstream( path.c_str() ) );
1077 }686 } else {
1078 else687 qstream.reset( new istringstream( uri ) );
1079 {
1080 qfile.reset(new std::istringstream(fURI));
1081 }688 }
1082689
1083 if (asFile && (!qfile->good() || qfile->eof()))690 if ( as_file && (!qstream->good() || qstream->eof()) ) {
1084 {691 cerr << "file {" << fname << "} not found or not readable." << endl;
1085 std::cerr << "file {" << fname << "} not found or not readable." << std::endl;692 print_help();
1086 properties.printHelp(std::cout);
1087 return 3;693 return 3;
1088 }694 } else if ( uri.empty() ) {
1089 else if (fURI.empty ())695 cerr << "empty query." << endl;
1090 {696 print_help();
1091 std::cerr << "empty query." << std::endl;
1092 properties.printHelp(std::cout);
1093 return 3;697 return 3;
1094 }698 }
1095699
1096 //700 //
1097 // Print the query if requested701 // Print the query if requested
1098 //702 //
1099 if (properties.printQuery()) 703 if ( zc_props.print_query_ ) {
1100 {704 *out_stream << "\nQuery number " << query_no << " :\n";
1101 *lOutputStream << "\nQuery number " << queryNo << " :\n";705 copy(
1102 std::copy (std::istreambuf_iterator<char> (*qfile),706 istreambuf_iterator<char>( *qstream ),
1103 std::istreambuf_iterator<char> (),707 istreambuf_iterator<char>(),
1104 std::ostreambuf_iterator<char> (*lOutputStream));708 ostreambuf_iterator<char>( *out_stream )
1105 *lOutputStream << std::endl;709 );
1106 // go back to the beginning710 *out_stream << endl;
1107 qfile->seekg(0);711 qstream->seekg( 0 );
1108 }712 }
1109713
1110 //714 //
1111 // Create the static context and populate it with info taken from the properties715 // Create the static context and populate it with info taken from the
716 // properties
1112 //717 //
1113 zorba::StaticContext_t lStaticContext = lZorbaInstance->createStaticContext();718 StaticContext_t sctx = zorba->createStaticContext();
1114719
1115 if (! populateStaticContext(lZorbaInstance, lStaticContext, properties) )720 if ( !populateStaticContext( zorba, sctx ) ) {
1116 {721 print_help();
1117 properties.printHelp(std::cout);
1118 return 3;722 return 3;
1119 }723 }
1120724
1121#ifdef DO_AUDIT725#ifdef DO_AUDIT
1122 zorba::audit::Event* event = lAuditProvider->createEvent(config);726 audit::Event *event = lAuditProvider->createEvent( config );
1123 lStaticContext->setAuditEvent(event);727 sctx->setAuditEvent( event );
1124#endif // DO_AUDIT728#endif // DO_AUDIT
1125729
1126 if (!asFile && properties.baseUri().size() == 0 )730 if ( !as_file && zc_props.base_uri_.empty() ) {
1127 {
1128 // No user set base URI. Set the cwd to be used as base-uri in order731 // No user set base URI. Set the cwd to be used as base-uri in order
1129 // to make the doc function doc("mydoc.xml") work732 // to make the doc function doc("mydoc.xml") work
1130 std::string p( fs::curdir() );733 string p( fs::curdir() );
1131 std::stringstream lTmp;734 stringstream lTmp;
1132 std::vector<std::string> lTokens;735 vector<string> lTokens;
1133 std::string const delim( 1, fs::dir_separator );736 tokenize( p, fs::dir_separator, &lTokens );
1134 Util::tokenize(p.c_str(), delim, lTokens);
1135737
1136 lTmp << "file://";738 lTmp << "file://";
1137 for (std::vector<std::string>::const_iterator lIter = lTokens.begin();739 for ( vector<string>::const_iterator i = lTokens.begin();
1138 lIter != lTokens.end(); ++lIter)740 i != lTokens.end(); ++i ) {
1139 {741 String s( *i );
1140 zorba::String lTmpString(*lIter);742 lTmp << '/' << fn::encode_for_uri( s );
1141 lTmp << '/' << fn::encode_for_uri( lTmpString );
1142 }743 }
1143744
1144 lTmp << '/';745 lTmp << '/';
1145746 sctx->setBaseURI( lTmp.str() );
1146 lStaticContext->setBaseURI(lTmp.str());
1147 }747 }
1148748
1149 // Parse the query749 // Parse the query
1150 if (properties.parseOnly()) 750 if ( zc_props.parse_only_ ) {
1151 {751 try {
1152 try 752 XQuery_t lQuery = zorba->createQuery();
1153 {753 if ( as_file )
1154 zorba::XQuery_t lQuery = lZorbaInstance->createQuery();754 lQuery->setFileName( path );
1155 if (asFile)
1156 {
1157 lQuery->setFileName(path);
1158 }
1159755
1160 lQuery->parse (*qfile);756 lQuery->parse (*qstream);
1161 }757 }
1162 catch (zorba::ZorbaException const& ze) 758 catch ( ZorbaException const &ze ) {
1163 {759 cerr << ze << endl;
1164 std::cerr << ze << std::endl;
1165 return 6;760 return 6;
1166 }761 }
1167 }762 }
1168763
1169 // Compile and run it if necessary.764 // Compile and run it if necessary.
1170 // Print timing information if requested.765 // Print timing information if requested.
1171 else if (!debug) 766 else if ( !debug ) {
1172 {767 if ( compile_only ) {
1173 if (compileOnly) 768 try {
1174 {769 XQuery_t aQuery = zorba->createQuery();
1175 try 770 if ( as_file )
1176 {771 aQuery->setFileName( path );
1177 zorba::XQuery_t aQuery = lZorbaInstance->createQuery();772
1178 if (asFile) 773 aQuery->parse( *qstream );
1179 {774 qstream->clear();
1180 aQuery->setFileName(path);775 qstream->seekg( 0 );
1181 }
1182
1183 aQuery->parse(*qfile);
1184
1185 qfile->clear();
1186 qfile->seekg(0); // go back to the beginning
1187 }776 }
1188 catch (zorba::XQueryException const& qe)777 catch ( XQueryException const &qe ) {
1189 {778 print_exception( qe );
1190 print_exception( qe, properties );
1191 return 6;779 return 6;
1192 }780 }
1193 }781 }
1194782
1195 TimingInfo queryTiming(properties.multiple());783 Timers queryTiming( zc_props.multiple_ );
1196784
1197 int status = compileAndExecute(lZorbaInstance,785 int status = compileAndExecute(zorba,
1198 xmlDataMgr,786 xmlDataMgr,
1199 properties,787 sctx,
1200 lStaticContext,
1201 path,788 path,
1202 *qfile,789 *qstream,
1203 *lOutputStream,790 *out_stream,
1204 queryTiming);791 queryTiming);
1205 if (status != 0) 792 if ( status != 0 ) {
1206 {
1207 // reset the file handler (in case output option was provided)793 // reset the file handler (in case output option was provided)
1208 // in order to delete the created output file794 // in order to delete the created output file
1209 lFileStream.reset();795 out_stream_ptr.reset();
1210 removeOutputFileIfNeeded(properties);796 remove_output_file();
1211 return status;797 return status;
1212 }798 }
1213799
1214 if (doTiming) 800 if ( zc_props.timing_ )
1215 {801 queryTiming.print( cout, zc_props.serialize_plan_ );
1216 bool serializePlan = properties.serializePlan();
1217 queryTiming.print(std::cout, serializePlan);
1218 }
1219 }802 }
1220803
1221#ifdef ZORBA_WITH_DEBUGGER804#ifdef ZORBA_WITH_DEBUGGER
1222 // Debug the query. Do not allow "compileOnly" flags and inline queries805 // Debug the query. Do not allow "compile_only" flags and inline queries
1223 else if (debug) 806 else if ( debug ) {
1224 {807 if ( compile_only ) {
1225 if (compileOnly) 808 cerr << "cannot debug a query if the --compile-only option is specified"
1226 {809 << endl;
1227 std::cerr << "cannot debug a query if the compileOnly option is specified"
1228 << std::endl;
1229 return 7;810 return 7;
1230 }811 }
1231812
1232 if (!asFile) 813 if ( !as_file ) {
1233 {814 cerr << "Cannot debug inline queries." << endl;
1234 std::cerr << "Cannot debug inline queries." << std::endl;
1235 return 8;815 return 8;
1236 }816 }
1237817
1238 std::unique_ptr<std::istream> lXQ(new std::ifstream(path.c_str()));818 unique_ptr<istream> lXQ( new ifstream( path.c_str() ) );
1239 std::string lFileName(path);819
1240820 XQuery_t query;
1241 zorba::XQuery_t lQuery;821
1242822 try {
1243 try 823 query = zorba->createQuery();
1244 {824 query->setFileName( path );
1245 lQuery = lZorbaInstance->createQuery();825 query->setDebugMode( true );
1246 lQuery->setFileName(lFileName);826
1247 lQuery->setDebugMode(true);827 Zorba_CompilerHints hints;
1248828 hints.opt_level = ZORBA_OPT_LEVEL_O0;
1249 Zorba_CompilerHints lHints;829
1250 lHints.opt_level = ZORBA_OPT_LEVEL_O0;830 query->compile( *lXQ.get(), hints );
1251831 if (!populateDynamicContext(zorba, xmlDataMgr,
1252 lQuery->compile(*lXQ.get(), lHints);832 query->getDynamicContext()))
1253 zorba::DynamicContext* lDynamicContext = lQuery->getDynamicContext();
1254 if (!populateDynamicContext(lZorbaInstance,
1255 xmlDataMgr,
1256 lDynamicContext,
1257 properties))
1258 {833 {
1259 return 9;834 return 9;
1260 }835 }
1261836
1262 std::string lHost = properties.debugHost();837 Zorba_SerializerOptions ser_opts( zc_props.serialization_params_ );
1263 if (lHost == "") {838 set_serializer_opts( ser_opts );
1264 lHost = "127.0.0.1";839
1265 }840 if ( !zc_props.no_logo_ )
1266841 cout << "Zorba XQuery Debugger Server\n" << copyright << endl;
1267 Zorba_SerializerOptions lSerOptions(properties.getSerializerParameters());842
1268 createSerializerOptions(lSerOptions, properties);843 query->debug( *out_stream, ser_opts, zc_props.debug_host_, zc_props.debug_port_ );
1269
1270 if (!properties.hasNoLogo())
1271 {
1272 std::cout << "Zorba XQuery Debugger Server\n" << copyright_str << std::endl;
1273 }
1274
1275 lQuery->debug(*lOutputStream, lSerOptions, lHost, properties.getDebugPort());
1276 }844 }
1277 catch (zorba::XQueryException const& qe)845 catch ( XQueryException const &qe ) {
1278 {846 print_exception( qe );
1279 print_exception( qe, properties );
1280 return 5;847 return 5;
1281 }848 }
1282 catch (zorba::ZorbaException const& ze)849 catch ( ZorbaException const &ze ) {
1283 {850 cerr << ze << endl;
1284 std::cerr << ze << std::endl;
1285 return 6;851 return 6;
1286 }852 }
1287 } // else if (debug)853 } // else if (debug)
1288#endif854#endif /* ZORBA_WITH_DEBUGGER */
1289855
1290#ifdef DO_AUDIT856#ifdef DO_AUDIT
1291 lAuditProvider->submitEvent(event);857 lAuditProvider->submitEvent( event );
1292#endif858#endif
1293859
1294 } // for each query860 } // for each query
1295861
1296 }862 }
1297863
1298 if (doTiming)864 if ( zc_props.timing_ )
1299 {865 timers.startTimer( Timers::deinit, 2 );
1300 engineTiming.startTimer(TimingInfo::DEINIT_TIMER, 2);
1301 }
1302866
1303#ifdef DO_AUDIT867#ifdef DO_AUDIT
1304 lAuditProvider->destroyConfiguration(config);868 lAuditProvider->destroyConfiguration(config);
1305#endif869#endif /* DO_AUDIT */
1306870
1307 xmlDataMgr = NULL;871 zorba->shutdown();
1308872 StoreManager::shutdownStore( store );
1309 lZorbaInstance->shutdown();873
1310 zorba::StoreManager::shutdownStore(store);874 if ( zc_props.timing_ ) {
1311875 timers.stopTimer( Timers::deinit, 2 );
1312 if (doTiming)876
1313 {877 cout << endl << "Engine Shutdown Time : "
1314 engineTiming.stopTimer(TimingInfo::DEINIT_TIMER, 2);878 << timers.elapsed_deinit_walltime
1315879 << " (user: " << timers.elapsed_deinit_cputime << ")"
1316 std::cout << std::endl << "Engine Shutdown Time : "880 << " milliseconds" << endl;
1317 << engineTiming.elapsedDeinitWalltime
1318 << " (user: " << engineTiming.elapsedDeinitCputime << ")"
1319 << " milliseconds" << std::endl;
1320 }881 }
882
1321 return 0;883 return 0;
1322}884}
885
886///////////////////////////////////////////////////////////////////////////////
887
1323/* vim:set et sw=2 ts=2: */888/* vim:set et sw=2 ts=2: */
1324889
=== added file 'bin/zorbacmd_args.cpp'
--- bin/zorbacmd_args.cpp 1970-01-01 00:00:00 +0000
+++ bin/zorbacmd_args.cpp 2014-02-11 00:42:47 +0000
@@ -0,0 +1,783 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// standard
18#include <algorithm>
19#include <cstdlib>
20#include <cctype>
21#include <iostream>
22
23// Zorba
24#include <zorba/zorba.h>
25#include <zorba/properties.h>
26
27// local
28#include "zorbacmd_props.h"
29
30using namespace std;
31using namespace zorba;
32
33///////////////////////////////////////////////////////////////////////////////
34
35static char const* check_args() {
36 ZorbaCmdProperties const &zc_props = ZorbaCmdProperties::instance();
37
38 if ( !( zc_props.boundary_space_.empty() ||
39 zc_props.boundary_space_ == "preserve" ||
40 zc_props.boundary_space_ == "strip" ) )
41 return "Only strip and preserve are allowed as values for the option boundary-space";
42
43 if ( !( zc_props.construction_mode_.empty() ||
44 zc_props.construction_mode_ == "preserve" ||
45 zc_props.construction_mode_ == "strip" ) )
46 return "Only strip and preserve are allowed as values for the option construction-mode";
47
48 if ( zc_props.optimization_level_ > 2 )
49 return "only 0, 1 and 2 are allowed as values for the option --optimization-level";
50
51 if ( !( zc_props.ordering_mode_.empty() ||
52 zc_props.ordering_mode_ == "ordered" ||
53 zc_props.ordering_mode_ == "unordered" ) )
54 return "Only ordered and unordered are allowed as values for the option ordering-mode";
55
56 if ( zc_props.queries_or_files_.empty() )
57 return "No queries submitted\nUsage: zorba -q '1 + 1' execute an inline query \n zorba file.xq execute a query from a file";
58
59 return 0;
60}
61
62///////////////////////////////////////////////////////////////////////////////
63
64#define HELP_OPT(ARG) ARG "\n"
65
66char const* get_help_msg() {
67 return
68
69 ////////// a //////////////////////////////////////////////////////////////
70
71#ifndef NDEBUG
72 HELP_OPT( "--abort" )
73 "Call abort(3) when a ZorbaException is thrown.\n\n"
74#endif /* NDEBUG */
75
76 HELP_OPT( "--as-files, -f" )
77 "Treat all -q arguments as file paths instead of URIs or inline queries. This option is deprecated and will be defaulted to true in the future, so any entry in the command line is going to be treated as files.\n\n"
78
79 ////////// b //////////////////////////////////////////////////////////////
80
81 HELP_OPT( "--base-uri" )
82 "Set the base URI property of the static context.\n\n"
83
84 HELP_OPT( "--boundary-space" )
85 "Set the boundary-space policy ('strip' or 'preserve') in the static context.\n\n"
86
87 HELP_OPT( "--byte-order-mark" )
88 "Set the byte-order-mark for the serializer.\n\n"
89
90 ////////// c //////////////////////////////////////////////////////////////
91
92 HELP_OPT( "--classpath" )
93 "JVM classpath to be used by modules using Java implementations\n\n"
94
95 HELP_OPT( "--compile-only" )
96 "Only compile (don't execute).\n\n"
97
98 HELP_OPT( "--compile-plan," )
99 "Do not execute the query; just compile it and save the execution plan in the file specified with the -o option.\n\n"
100
101 HELP_OPT( "--construction-mode" )
102 "Set the construction mode ('strip' or 'preserve') in the static context.\n\n"
103
104 HELP_OPT( "--context-item" )
105 "Set the context item to the XML document in a given file.\n\n"
106
107 ////////// d //////////////////////////////////////////////////////////////
108
109#ifdef ZORBA_WITH_DEBUGGER
110 HELP_OPT( "--debug, -d" )
111 "Launch the Zorba debugger server and connect to a DBGP-enabled debugger client.\n\n"
112#endif /* ZORBA_WITH_DEBUGGER */
113
114 HELP_OPT( "--debug-file" )
115 "Sets the file to write developer debugging information to.\n\n"
116
117#ifdef ZORBA_WITH_DEBUGGER
118 HELP_OPT( "--debug-host, -h" )
119 "The host where the DBGP-enabled debugger client listens for connections. Defaults to: 127.0.0.1\n\n"
120
121 HELP_OPT( "--debug-port, -p" )
122 "The port on which the DBGP-enabled debugger client listens for connections. Defaults to: 28028\n\n"
123#endif /* ZORBA_WITH_DEBUGGER */
124
125 HELP_OPT( "--default-collation" )
126 "Add the given collation and set the value of the default collation in the static context to the given collation.\n\n"
127
128 HELP_OPT( "--disable-http-resolution" )
129 "Do not use HTTP to resolve URIs.\n\n"
130
131 HELP_OPT( "--dump-lib" )
132 "Dump function library.\n\n"
133
134 ////////// e //////////////////////////////////////////////////////////////
135
136 HELP_OPT( "--execute-plan" )
137 "Do not compile the query; instead load the execution plan from the file specified by the -f -q options (or by any file specified without any other argument), and execute the loaded plan.\n\n"
138
139 HELP_OPT( "--external-variable, -e" )
140 "Provide the value for a variable given a file (name=file) or a value (name:=value)\n\n"
141
142 ////////// f //////////////////////////////////////////////////////////////
143
144 HELP_OPT( "--force-gflwor" )
145 "Force the compiler to generate GFLWOR iterators.\n\n"
146
147 ////////// h //////////////////////////////////////////////////////////////
148
149 HELP_OPT( "--help, -h" )
150 "Print this help message.\n\n"
151
152 ////////// i //////////////////////////////////////////////////////////////
153
154 HELP_OPT( "--indent, -i" )
155 "Indent output.\n\n"
156
157 HELP_OPT( "--infer-joins" )
158 "Infer joins.\n\n"
159
160 HELP_OPT( "--inline-udf" )
161 "Inline user-defined functions.\n\n"
162
163 ////////// j //////////////////////////////////////////////////////////////
164
165 HELP_OPT( "--jsoniq, -j" )
166 "Force queries to be considered JSONiq.\n\n"
167
168 ////////// l //////////////////////////////////////////////////////////////
169
170 HELP_OPT( "--lib-module, -l" )
171 "Query compiler option to treat the query as a library module. If this is set --compile-only option is also set to true.\n\n"
172
173 HELP_OPT( "--lib-path" )
174 "Library path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.\n\n"
175
176 HELP_OPT( "--loop-hosting" )
177 "Hoist expressions out of loops.\n\n"
178
179 ////////// m //////////////////////////////////////////////////////////////
180
181 HELP_OPT( "--max-udf-call-depth" )
182 "Maximum stack depth of user-defined function calls.\n\n"
183
184 HELP_OPT( "--module-path" )
185 "Path (list of directories) to add to both the URI and Library paths.\n\n"
186
187 HELP_OPT( "--multiple, -m" )
188 "Execute the given queries multiple times.\n\n"
189
190 ////////// n //////////////////////////////////////////////////////////////
191
192 HELP_OPT( "--no-copy-optim" )
193 "Apply the no-copy optimization.\n\n"
194
195 HELP_OPT( "--no-logo" )
196 "Print no logo when starting.\n\n"
197
198 HELP_OPT( "--no-serializer" )
199 "Do not serialize (discard) result.\n\n"
200
201 HELP_OPT( "--no-tree-ids" )
202 "Suppress IDs and locations from compiler tree dumps.\n\n"
203
204 ////////// o //////////////////////////////////////////////////////////////
205
206 HELP_OPT( "--omit-xml-declaration, -r" )
207 "Omit the XML declaration from the result.\n\n"
208
209 HELP_OPT( "--optimization-level, -O" )
210 "Optimization level for the query compiler [0-2], default: 1\n\n"
211
212 HELP_OPT( "--option" )
213 "Set an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://zorba.io/}option=value\n\n"
214
215 HELP_OPT( "--ordering-mode" )
216 "Set the ordering mode ('ordered' or 'unordered') in the static context.\n\n"
217
218#ifdef ZORBA_WITH_FILE_ACCESS
219 HELP_OPT( "--output-file, -o" )
220 "Write the result to the given file.\n\n"
221#endif /* ZORBA_WITH_FILE_ACCESS */
222
223 ////////// p //////////////////////////////////////////////////////////////
224
225 HELP_OPT( "--parse-only" )
226 "Stop after parsing the query.\n\n"
227
228 HELP_OPT( "--print-ast" )
229 "Print the abstract syntax tree.\n\n"
230
231 HELP_OPT( "--print-errors-as-xml, -x" )
232 "Print the errors as XML.\n\n"
233
234 HELP_OPT( "--print-intermediate-opt" )
235 "Print intermediate optimizations.\n\n"
236
237 HELP_OPT( "--print-item-flow" )
238 "Print items produced by all iterators.\n\n"
239
240 HELP_OPT( "--print-iterator-tree" )
241 "Print the iterator tree.\n\n"
242
243 HELP_OPT( "--print-locations" )
244 "Print parser locations for compiler expressions.\n\n"
245
246 HELP_OPT( "--print-optimized" )
247 "Print the optimized expression tree.\n\n"
248
249 HELP_OPT( "--print-query" )
250 "Print the queries.\n\n"
251
252 HELP_OPT( "--print-static-types" )
253 "Print static type inference.\n\n"
254
255 HELP_OPT( "--print-translated" )
256 "Print the normalized expression tree.\n\n"
257
258 ////////// q //////////////////////////////////////////////////////////////
259
260 HELP_OPT( "--query, -q" )
261 "Query test or file URI (file://...)\n\n"
262
263 ////////// s //////////////////////////////////////////////////////////////
264
265 HELP_OPT( "--serialization-parameter, -z" )
266 "Set serialization parameter in the form of a parameter=value pair (see http://www.w3.org/TR/xslt-xquery-serialization/#serparam, e.g.: -z method=xhtml -z doctype-system=DTD/xhtml1-strict.dtd -z indent=yes).\n\n"
267
268 HELP_OPT( "--serialize-html" )
269 "Serialize the result as HTML.\n\n"
270
271 HELP_OPT( "--serialize-plan, -s" )
272 "Serialize and then load the query execution plan.\n\n"
273
274 HELP_OPT( "--serialize-only-query" )
275 "Serialize only query.\n\n"
276
277 HELP_OPT( "--serialize-plan, s" )
278 "Serialize and then load the query execution plan.\n\n"
279
280 HELP_OPT( "--serialize-text" )
281 "Serialize the result as text.\n\n"
282
283 HELP_OPT( "--stable-iterator-ids" )
284 "Print the iterator plan with stable IDs.\n\n"
285
286#ifndef ZORBA_NO_FULL_TEXT
287 HELP_OPT( "--stop-words" )
288 "Mapping specifying a stop-words URI to another.\n\n"
289
290 ////////// t //////////////////////////////////////////////////////////////
291
292 HELP_OPT( "--thesaurus" )
293 "Mapping specifying a thesaurus URI to another.\n\n"
294#endif /* ZORBA_NO_FULL_TEXT */
295
296 HELP_OPT( "--timing, -t" )
297 "Print timing information. In case of multiple queries, the timing information is provided per query. Both wallclock time and user time (which excludes I/O, network delays and other kernel waits) are shown.\n\n"
298
299 HELP_OPT( "--timeout" )
300 "Specify a timeout in seconds. After the specified time, the execution of the query will be aborted.\n\n"
301
302 HELP_OPT( "--trace-parsing" )
303 "Trace parsing.\n\n"
304
305 HELP_OPT( "--trace-scanning" )
306 "Trace scanning.\n\n"
307
308#ifndef NDEBUG
309 HELP_OPT( "--trace-codegen" )
310 "Trace code generatio.\n\n"
311
312 HELP_OPT( "--trace-fulltext" )
313 "Trace full-text.\n\n"
314
315 HELP_OPT( "--trace-translator" )
316 "Trace the translator.\n\n"
317#endif /* NDEBUG */
318
319 HELP_OPT( "--trailing-nl" )
320 "Print a trailing newline after the result of the query.\n\n"
321
322 ////////// u //////////////////////////////////////////////////////////////
323
324 HELP_OPT( "--uri-path" )
325 "URI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.\n\n"
326
327 ////////// v //////////////////////////////////////////////////////////////
328
329 HELP_OPT( "--version, -v" )
330 "Print the version number and exit.\n\n"
331
332 ;
333}
334
335///////////////////////////////////////////////////////////////////////////////
336
337static bool split_key_value( char const *s, char const *split,
338 string *key, string *value ) {
339 char const *const p = strstr( s, split );
340 size_t const split_len = strlen( split );
341 if ( !p || p == s /* =xxx */ || !p[ split_len ] /* xxx= */ )
342 return false;
343 key->assign( s, 0, p - s );
344 value->assign( p + split_len );
345 return true;
346}
347
348inline char to_lower( char c ) {
349 return tolower( c );
350}
351
352template<class StringType> inline
353typename enable_if<ZORBA_IS_STRING(StringType),void>::type
354to_lower( StringType &s ) {
355 transform(
356 s.begin(), s.end(), s.begin(), static_cast<char (*)(char)>( to_lower )
357 );
358}
359
360static bool bool_of( char const *s ) {
361 string b( s );
362 to_lower( b );
363 if ( b == "t" || b == "true" || b == "y" || b == "yes" || b == "1" )
364 return true;
365 if ( b == "f" || b == "false" || b == "n" || b == "no" || b == "0" )
366 return false;
367 cerr << '"' << s << "\": invalid boolean value" << endl;
368 exit( 1 );
369}
370
371///////////////////////////////////////////////////////////////////////////////
372
373#define IS_LONG_OPT(OPT) (strcmp( *argv, (OPT) ) == 0)
374#define IS_SHORT_OPT(OPT) (strncmp( *argv, (OPT), 2 ) == 0)
375#define IS_OPT(LOPT,SOPT) (IS_LONG_OPT(LOPT) || IS_SHORT_OPT(SOPT))
376
377#define PARSE_ARG(ARG) \
378 int offset = 2; \
379 if ( (*argv)[1] == '-' || !(*argv)[2] ) { offset = 0; ++argv; } \
380 if ( !*argv ) { error = "No value given for " #ARG " option"; break; }
381
382#define ARG_VAL (*argv + offset)
383
384template<typename T> inline
385void atoi( char const *s, T *result, int offset = 0 ) {
386 istringstream iss( s + offset );
387 iss >> *result;
388}
389
390#define SET_ZCPROP(PROP) \
391 atoi( *argv, &zc_props.PROP, offset )
392
393template<class C,typename T> inline
394void atoi( char const *s, C &c, void (C::*f)( T ), int offset = 0 ) {
395 T temp;
396 atoi( s, &temp, offset );
397 (c.*f)( temp );
398}
399
400#define SET_ZPROP(PROP) \
401 atoi( *argv, z_props, &Properties::set##PROP, offset )
402
403int parse_args( int argc, char const *argv[] ) {
404 bool got_as_files = false;
405 char const *error = 0;
406 Properties &z_props = Properties::instance();
407 ZorbaCmdProperties &zc_props = ZorbaCmdProperties::instance();
408
409 char const **const argv_orig = argv;
410 for ( ++argv; *argv; ++argv ) {
411
412 ////////// a //////////////////////////////////////////////////////////////
413
414#ifndef NDEBUG
415 if ( IS_LONG_OPT( "--abort" ) )
416 z_props.setAbort( true );
417 else
418#endif /* NDEBUG */
419 if ( IS_OPT( "--as-files", "-f" ) ) {
420 zc_props.as_files_ = true;
421 got_as_files = true;
422 }
423
424 ////////// b //////////////////////////////////////////////////////////////
425
426 else if ( IS_LONG_OPT( "--base-uri" ) ) {
427 PARSE_ARG( "--base-uri" );
428 zc_props.base_uri_ = ARG_VAL;
429 }
430 else if ( IS_LONG_OPT( "--boundary-space" ) ) {
431 PARSE_ARG( "--boundary-space" );
432 zc_props.boundary_space_ = ARG_VAL;
433 }
434 else if ( IS_LONG_OPT( "--byte-order-mark" ) )
435 zc_props.byte_order_mark_ = true;
436
437 ////////// c //////////////////////////////////////////////////////////////
438
439 else if ( IS_LONG_OPT( "--classpath" ) ) {
440 PARSE_ARG( "--classpath" );
441 z_props.setJVMClassPath( ARG_VAL );
442 }
443 else if ( IS_LONG_OPT( "--compile-only" ) )
444 zc_props.compile_only_ = true;
445 else if ( IS_LONG_OPT( "--compile-plan" ) )
446 zc_props.save_plan_ = true;
447 else if ( IS_LONG_OPT( "--construction-mode" ) ) {
448 PARSE_ARG( "--construction-mode" );
449 zc_props.construction_mode_ = ARG_VAL;
450 }
451 else if ( IS_LONG_OPT( "--context-item" ) ) {
452 PARSE_ARG( "--context-item" );
453 zc_props.ctx_item_ = ARG_VAL;
454 }
455
456 ////////// d //////////////////////////////////////////////////////////////
457
458#ifdef ZORBA_WITH_DEBUGGER
459 else if ( IS_OPT( "--debug", "-d" ) )
460 zc_props.debug_ = true;
461#endif /* ZORBA_WITH_DEBUGGER */
462 else if ( IS_LONG_OPT( "--debug-file" ) ) {
463 PARSE_ARG( "--debug-file" );
464 z_props.setDebugFile( ARG_VAL );
465 }
466#ifdef ZORBA_WITH_DEBUGGER
467 else if ( IS_OPT( "--debug-host", "-h" ) ) {
468 PARSE_ARG( "--debug-host" );
469 zc_props.debug_host_ = ARG_VAL;
470 }
471 else if ( IS_OPT( "--debug-port", "-p" ) ) {
472 PARSE_ARG( "--debug-port" );
473 SET_ZCPROP( debug_port_ );
474 }
475#endif /* ZORBA_WITH_DEBUGGER */
476 else if ( IS_LONG_OPT( "--default-collation" ) ) {
477 PARSE_ARG( "--default-collation" );
478 zc_props.default_collation_ = ARG_VAL;
479 }
480 else if ( IS_LONG_OPT( "--disable-http-resolution" ) ) {
481 sctx_opt opt;
482 opt.clark_qname = "{http://zorba.io/options/features}disable";
483 opt.value = "http-uri-resolution";
484 zc_props.sctx_opts_.push_back( opt );
485 }
486 else if ( IS_LONG_OPT( "--dump-lib" ) )
487 z_props.setDumpLib( true );
488
489 ////////// e //////////////////////////////////////////////////////////////
490
491 else if ( IS_LONG_OPT( "--execute-plan" ) )
492 zc_props.load_plan_ = true;
493 else if ( IS_OPT( "--external-variable", "-e" ) ) {
494 PARSE_ARG( "--external-variable" );
495 string key, value;
496 if ( !split_key_value( ARG_VAL, "=", &key, &value ) ) {
497 error = "--external-variable argument must be of the form name=file or name:=value\n";
498 break;
499 }
500 external_var ev;
501 ev.var_value = value;
502
503 if ( key[0] == ':' ) {
504 error = "--external-variable argument must be of the form name=file or name:=value\n";
505 break;
506 }
507 if ( key[ key.size() - 1 ] == ':' )
508 key.erase( key.size() - 1 );
509 else
510 ev.inline_file = true;
511 ev.var_name = key;
512
513 zc_props.external_vars_.push_back( ev );
514 }
515
516 ////////// f //////////////////////////////////////////////////////////////
517
518 else if ( IS_LONG_OPT( "--force-gflwor" ) )
519 z_props.setForceGFLWOR( true );
520
521 ////////// h //////////////////////////////////////////////////////////////
522
523 else if ( IS_OPT( "--help", "-h" ) ) {
524 cout << "Zorba NoSQL Query Processor, Version: "
525 << Zorba::version() << '\n'
526 << "Available options:\n\n"
527 << get_help_msg();
528 exit( 0 );
529 }
530
531 ////////// i //////////////////////////////////////////////////////////////
532
533 else if ( IS_OPT( "--indent", "-i" ) )
534 zc_props.indent_ = true;
535 else if ( IS_LONG_OPT( "--infer-joins" ) ) {
536 PARSE_ARG( "--infer-joins" );
537 z_props.setInferJoins( bool_of( ARG_VAL ) );
538 }
539 else if ( IS_LONG_OPT( "--inline-udf" ) ) {
540 PARSE_ARG( "--inline-udf" );
541 z_props.setInlineUDF( bool_of( ARG_VAL ) );
542 }
543
544 ////////// j //////////////////////////////////////////////////////////////
545
546 else if ( IS_OPT( "--jsoniq", "-j" ) )
547 zc_props.jsoniq_ = true;
548
549 ////////// l //////////////////////////////////////////////////////////////
550
551 else if ( IS_OPT( "--lib-module", "-l" ) )
552 zc_props.lib_module_ = true;
553 else if ( IS_LONG_OPT( "--lib-path" ) ) {
554 PARSE_ARG( "--lib-path" );
555 zc_props.lib_path_ = ARG_VAL;
556 }
557 else if ( IS_LONG_OPT( "--loop-hoisting" ) ) {
558 PARSE_ARG( "--loop-hoisting" );
559 z_props.setLoopHoisting( bool_of( ARG_VAL ) );
560 }
561
562 ////////// m //////////////////////////////////////////////////////////////
563
564 else if ( IS_LONG_OPT( "--max-udf-call-depth" ) ) {
565 PARSE_ARG( "--max-udf-call-depth" );
566 SET_ZPROP( MaxUDFCallDepth );
567 }
568 else if ( IS_LONG_OPT( "--module-path" ) ) {
569 PARSE_ARG( "--module-path" );
570 zc_props.module_path_ = ARG_VAL;
571 }
572 else if ( IS_OPT( "--multiple", "-m" ) ) {
573 PARSE_ARG( "--multiple" );
574 SET_ZCPROP( multiple_ );
575 }
576
577 ////////// n //////////////////////////////////////////////////////////////
578
579 else if ( IS_LONG_OPT( "--no-copy-optim" ) ) {
580 PARSE_ARG( "--no-copy-optim" );
581 z_props.setNoCopyOptim( bool_of( ARG_VAL ) );
582 }
583 else if ( IS_LONG_OPT( "--no-logo" ) )
584 zc_props.no_logo_ = true;
585 else if ( IS_LONG_OPT( "--no-serializer" ) )
586 zc_props.no_serializer_ = true;
587 else if ( IS_LONG_OPT( "--no-tree-ids" ) )
588 z_props.setNoTreeIDs( true );
589
590 ////////// o //////////////////////////////////////////////////////////////
591
592 else if ( IS_OPT( "--omit-xml-declaration", "-r" ) )
593 zc_props.omit_xml_declaration_ = true;
594 else if ( IS_OPT( "--optimization-level", "-O" ) ) {
595 PARSE_ARG( "--optimization-level" );
596 unsigned opt_level;
597 atoi( ARG_VAL, &opt_level );
598 if ( opt_level > 2 ) {
599 error = "Only 0, 1 and 2 are allowed as values for --optimization-level";
600 break;
601 }
602 z_props.setOptimizationLevel( opt_level );
603 }
604 else if ( IS_LONG_OPT( "--option" ) ) {
605 PARSE_ARG( "--option" );
606 string key, value;
607 if ( !split_key_value( ARG_VAL, "=", &key, &value ) ) {
608 error = "--option argument must be of the form {namespace}localname=value\n";
609 break;
610 }
611 // TODO: check key is of the form {ns}local
612 sctx_opt opt;
613 opt.clark_qname = key;
614 opt.value = value;
615 zc_props.sctx_opts_.push_back( opt );
616 }
617 else if ( IS_LONG_OPT( "--ordering-mode" ) ) {
618 PARSE_ARG( "--ordering-mode" );
619 zc_props.ordering_mode_ = ARG_VAL;
620 }
621#ifdef ZORBA_WITH_FILE_ACCESS
622 else if ( IS_OPT( "--output-file", "-o" ) ) {
623 PARSE_ARG( "--output-file" );
624 zc_props.output_file_ = ARG_VAL;
625 }
626#endif /* ZORBA_WITH_FILE_ACCESS */
627
628 ////////// p //////////////////////////////////////////////////////////////
629
630 else if ( IS_LONG_OPT( "--parse-only" ) )
631 zc_props.parse_only_ = true;
632 else if ( IS_OPT( "--print-ast", "-a" ) )
633 z_props.setPrintAST( true );
634 else if ( IS_OPT( "--print-errors-as-xml", "-x" ) )
635 zc_props.print_errors_as_xml_ = true;
636 else if ( IS_LONG_OPT( "--print-intermediate-opt" ) )
637 z_props.setPrintIntermediateOpt( true );
638 else if ( IS_LONG_OPT( "--print-item-flow" ) )
639 z_props.setPrintItemFlow( true );
640 else if ( IS_LONG_OPT( "--print-iterator-tree" ) )
641 z_props.setPrintIteratorTree( true );
642 else if ( IS_LONG_OPT( "--print-locations" ) )
643 z_props.setPrintLocations( true );
644 else if ( IS_OPT( "--print-optimized", "-P" ) )
645 z_props.setPrintOptimized( true );
646 else if ( IS_LONG_OPT( "--print-query" ) )
647 zc_props.print_query_ = true;
648 else if ( IS_LONG_OPT( "--print-static-types" ) )
649 z_props.setPrintStaticTypes( true );
650 else if ( IS_LONG_OPT( "--print-translated" ) )
651 z_props.setPrintTranslated( true );
652
653 ////////// q //////////////////////////////////////////////////////////////
654
655 else if ( IS_OPT( "--query", "-q" ) ) {
656 if ( !got_as_files )
657 zc_props.as_files_ = false;
658 if ( *(argv+1) && !strncmp( *(argv+1), "-f", 2 ) )
659 break; // is it "-q -f <filename>" perhaps?
660 PARSE_ARG( "--query" );
661 zc_props.queries_or_files_.push_back( ARG_VAL );
662 }
663
664 ////////// s //////////////////////////////////////////////////////////////
665
666 else if ( IS_OPT( "--serialization-parameter", "-z" ) ) {
667 PARSE_ARG( "--serialization-parameter" );
668 string key, value;
669 serialization_param sp;
670 if ( split_key_value( ARG_VAL, "=", &key, &value ) ) {
671 sp.first = key;
672 sp.second = value;
673 } else
674 sp.first = ARG_VAL;
675 zc_props.serialization_params_.push_back( sp );
676 }
677 else if ( IS_LONG_OPT( "--serialize-html" ) )
678 zc_props.serialize_html_ = true;
679 else if ( IS_LONG_OPT( "--serialize-only-query" ) ) {
680 PARSE_ARG( "--serialize-only-query" );
681 zc_props.serialize_only_query_ = bool_of( ARG_VAL );
682 }
683 else if ( IS_OPT( "--serialize-plan", "-s" ) )
684 zc_props.serialize_plan_ = true;
685 else if ( IS_LONG_OPT( "--serialize-text" ) )
686 zc_props.serialize_text_ = true;
687 else if ( IS_LONG_OPT( "--stable-iterator-ids" ) )
688 z_props.setStableIteratorIDs( true );
689#ifndef ZORBA_NO_FULL_TEXT
690 else if ( IS_LONG_OPT( "--stop-words" ) ) {
691 PARSE_ARG( "--stop-words" );
692 string uri, value;
693 if ( !split_key_value( ARG_VAL, ":=", &uri, &value ) ) {
694 error = "--stop-words argument must be of the form URI:=value\n";
695 break;
696 }
697 ft_mapping ft;
698 ft.uri = uri;
699 ft.value = value;
700 zc_props.stop_words_mapping_.push_back( ft );
701 }
702
703 ////////// t //////////////////////////////////////////////////////////////
704
705 else if ( IS_LONG_OPT( "--thesaurus" ) ) {
706 PARSE_ARG( "--thesaurus" );
707 string uri, value;
708 if ( !split_key_value( ARG_VAL, ":=", &uri, &value ) ) {
709 error = "--thesaurus argument must be of the form URI:=value\n";
710 break;
711 }
712 if ( uri == "default" )
713 uri = "##default";
714 ft_mapping ft;
715 ft.uri = uri;
716 ft.value = value;
717 zc_props.thesaurus_mapping_.push_back( ft );
718 }
719#endif /* ZORBA_NO_FULL_TEXT */
720 else if ( IS_OPT( "--timing", "-t" ) )
721 zc_props.timing_ = true;
722 else if ( IS_LONG_OPT( "--timeout" ) ) {
723 PARSE_ARG( "--timeout" );
724 SET_ZCPROP( timeout_ );
725 }
726 else if ( IS_LONG_OPT( "--trace-parsing" ) )
727 z_props.setTraceParsing( true );
728 else if ( IS_LONG_OPT( "--trace-scanning" ) )
729 z_props.setTraceScanning( true );
730#ifndef NDEBUG
731 else if ( IS_LONG_OPT( "--trace-codegen" ) )
732 z_props.setTraceCodegen( true );
733 else if ( IS_LONG_OPT( "--trace-fulltext" ) )
734 z_props.setTraceFulltext( true );
735 else if ( IS_LONG_OPT( "--trace-translator" ) )
736 z_props.setTraceTranslator( true );
737#endif /* NDEBUG */
738 else if ( IS_LONG_OPT( "--trailing-nl" ) )
739 zc_props.trailing_nl_ = true;
740
741 ////////// u //////////////////////////////////////////////////////////////
742
743 else if ( IS_LONG_OPT( "--uri-path" ) ) {
744 PARSE_ARG( "--uri-path" );
745 zc_props.uri_path_ = ARG_VAL;
746 }
747 else if ( IS_LONG_OPT( "--use-indexes" ) ) {
748 PARSE_ARG( "--use-indexes" );
749 z_props.setUseIndexes( true );
750 }
751
752 ////////// v //////////////////////////////////////////////////////////////
753
754 else if ( IS_OPT( "--version", "-v" ) ) {
755 cout << "Zorba NoSQL Query Processor, Version: "
756 << zorba::Zorba::version() << endl;
757 exit( 1 ); // should be 0, but the old code returned 1
758 }
759
760 ////////// END ////////////////////////////////////////////////////////////
761
762 else if ( IS_LONG_OPT( "--" ) )
763 break;
764 else if ( (*argv)[0] == '-' ) {
765 cerr << "unknown command line option " << *argv << endl;
766 exit( 1 );
767 } else {
768 zc_props.queries_or_files_.push_back( *argv );
769 }
770 } // for
771
772 if ( !error )
773 error = check_args();
774 if ( error ) {
775 cout << "Error: " << error << "\nUse -h for help." << endl;
776 exit( 1 );
777 }
778 return argv - argv_orig;
779}
780
781///////////////////////////////////////////////////////////////////////////////
782
783/* vim:set et sw=2 ts=2: */
0784
=== renamed file 'bin/zorbacmdproperties.cpp' => 'bin/zorbacmd_props.cpp'
--- bin/zorbacmdproperties.cpp 2013-06-16 00:37:21 +0000
+++ bin/zorbacmd_props.cpp 2014-02-11 00:42:47 +0000
@@ -13,202 +13,48 @@
13 * See the License for the specific language governing permissions and13 * See the License for the specific language governing permissions and
14 * limitations under the License.14 * limitations under the License.
15 */15 */
16#include "zorbacmdproperties.h"16
1717// local
18#include <fstream>18#include "zorbacmd_props.h"
19#include <iostream>19
20#include <cstdlib>20///////////////////////////////////////////////////////////////////////////////
2121
22#include <zorba/zorba.h>22ZorbaCmdProperties::ZorbaCmdProperties() {
2323 as_files_ = true;
24std::string ZorbaCMDProperties::check_args () {24 byte_order_mark_ = false;
2525 compile_only_ = false;
26 if(queriesOrFilesBegin() == queriesOrFilesEnd())26#ifdef ZORBA_WITH_DEBUGGER
27 {27 debug_ = false;
28 return "No queries submitted \nUsage: zorba -q '1 + 1' execute an inline query \n zorba file.xq execute a query from a file \n Use -h for help.";28 debug_host_ = "127.0.0.1";
29 }29 debug_port_ = 28028;
3030#endif /* ZORBA_WITH_DEBUGGER */
31 if(unknownOption())31 indent_ = false;
32 {32 jsoniq_ = false;
33 return "Extra arguments found on command line. Use -h for help.";33 lib_module_ = false;
34 }34 load_plan_ = false;
3535 multiple_ = 1;
36 if(queriesOrFilesBegin() == queriesOrFilesEnd())36 no_logo_ = false;
37 {37 no_serializer_ = false;
38 return "No queries submitted \nUsage: zorba -q '1 + 1' execute an inline query \n zorba file.xq execute a query from a file \n Use -h for help.";38 omit_xml_declaration_ = false;
39 }39 optimization_level_ = 1;
4040 parse_only_ = false;
41 if ( theBoundarySpace.size() != 0 )41 print_errors_as_xml_ = false;
42 {42 print_query_ = false;
43 if ( ! (theBoundarySpace.compare("strip") == 0 || theBoundarySpace.compare("preserve") == 0 ))43 save_plan_ = false;
44 return "Only strip and preserve are allowed as values for the option boundary-space";44 serialize_html_ = false;
45 }45 serialize_only_query_ = false;
4646 serialize_plan_ = false;
47 if ( theConstructionMode.size() != 0 )47 serialize_text_ = false;
48 {48 timeout_ = -1;
49 if ( ! (theConstructionMode.compare("strip") == 0 || theConstructionMode.compare("preserve") == 0 ))49 timing_ = false;
50 return "Only strip and preserve are allowed as values for the option construction-mode";50 trailing_nl_ = false;
51 }51}
5252
53 if ( theOrderingMode.size() != 0 ) {53ZorbaCmdProperties& ZorbaCmdProperties::instance() {
54 if ( ! (theOrderingMode.compare("ordered") == 0 || theOrderingMode.compare("unordered") == 0 ))54 static ZorbaCmdProperties instance;
55 return "Only ordered and unordered are allowed as values for the option ordering-mode";55 return instance;
56 }56}
5757
58 if ( ! (theOptimizationLevel.compare("O0") == 0 || theOptimizationLevel.compare("O1") == 058///////////////////////////////////////////////////////////////////////////////
59 || theOptimizationLevel.compare("O2") == 0 ) )59
60 return "only O0, O1 and O2 are allowed as values for the option opt-level";60/* vim:set et sw=2 ts=2: */
61
62 for (std::vector<std::string>::const_iterator lIter = theExternalVariable.begin();
63 lIter != theExternalVariable.end(); ++lIter)
64 {
65 std::string lStr = *lIter;
66 std::string::size_type lPos = lStr.find_first_of("=");
67 std::string lVarName = lStr.substr(0, lPos);
68 std::string lValue = lStr.substr(lPos + 1);
69 bool lInlineFile = true;
70 if (lVarName.at(lVarName.size()-1) == ':')
71 {
72 lInlineFile = false;
73 lVarName.resize(lVarName.size()-1); // remove the :
74 }
75 ExternalVariable lExternalVariable;
76 lExternalVariable.var_name = lVarName;
77 lExternalVariable.var_value = lValue;
78 lExternalVariable.inline_file = lInlineFile;
79 theExternalVars.push_back(lExternalVariable);
80 }
81
82 for (std::vector<std::string>::const_iterator lIter = theOption.begin();
83 lIter != theOption.end(); ++lIter)
84 {
85 size_t lEQual = lIter->find_last_of("=");
86 if (lEQual == std::string::npos)
87 return "option must be of the form {namespace}localname=value";
88
89 std::string lClarkQName = lIter->substr(0, lEQual);
90 std::string lValue = lIter->substr(lEQual + 1);
91
92 StaticContextOption lOption;
93 lOption.clark_qname = lClarkQName;
94 lOption.value = lValue;
95 theStaticContextOptions.push_back(lOption);
96 }
97
98 for (std::vector<std::string>::const_iterator lIter = theStopWords.begin();
99 lIter != theStopWords.end(); ++lIter)
100 {
101 size_t lEQual = lIter->find(":=");
102 if (lEQual == std::string::npos)
103 return "Stop-words mapping must be of the form URI:=value";
104
105 std::string lURI = lIter->substr(0, lEQual);
106 std::string lValue = lIter->substr(lEQual + 2);
107
108 FullTextMapping lMapping;
109 lMapping.uri = lURI;
110 lMapping.value = lValue;
111 theStopWordsMapping.push_back(lMapping);
112 }
113
114 for (std::vector<std::string>::const_iterator lIter = theThesaurus.begin();
115 lIter != theThesaurus.end(); ++lIter)
116 {
117 size_t lEQual = lIter->find(":=");
118 if (lEQual == std::string::npos)
119 return "Thesaurus mapping must be of the form URI:=value";
120
121 std::string lURI = lIter->substr(0, lEQual);
122 std::string lValue = lIter->substr(lEQual + 2);
123
124 if ( lURI == "default" )
125 lURI = "##default";
126
127 FullTextMapping lMapping;
128 lMapping.uri = lURI;
129 lMapping.value = lValue;
130 theThesaurusMapping.push_back(lMapping);
131 }
132
133 return "";
134}
135
136
137bool ZorbaCMDProperties::loadProperties(int argc, char* argv[])
138{
139 std::string result = load_argv(argc, (const char **) argv);
140
141 if (result.empty())
142 result = check_args();
143
144 if (result == "!HELP")
145 {
146 std::cout << "Zorba NoSQL Query Processor, Version: "
147 << zorba::Zorba::version() << std::endl;
148 std::cout << "Available options:\n\n";
149 std::cout << get_help_msg ();
150 return false;
151 }
152 else if (result == "!VER")
153 {
154 std::cout << "Zorba NoSQL Query Processor, Version: "
155 << zorba::Zorba::version() << std::endl;
156 return false;
157 }
158 else if (result.empty ())
159 {
160 return true;
161 }
162 else if (result [0] != '!')
163 {
164 std::cout << "Error: " << result << std::endl;
165 return false;
166 }
167 else
168 {
169 return false;
170 }
171}
172
173
174void ZorbaCMDProperties::getModulePath(std::string& aPath) const
175{
176 aPath = theModulePath;
177}
178
179void ZorbaCMDProperties::getURIPath(std::string& aPath) const
180{
181 aPath = theUriPath;
182}
183
184void ZorbaCMDProperties::getLibPath(std::string& aPath) const
185{
186 aPath = theLibPath;
187}
188
189void ZorbaCMDProperties::getJVMClassPath(std::string& aPath) const
190{
191 aPath = theClasspath;
192}
193
194std::vector<std::pair<std::string,std::string> > ZorbaCMDProperties::getSerializerParameters() const
195{
196 std::vector<std::pair<std::string,std::string> > lResult;
197 std::vector<std::string>::const_iterator lEnd = theSerializationParameter.end();
198 for (
199 std::vector<std::string>::const_iterator lIter = theSerializationParameter.begin();
200 lIter != lEnd;
201 ++lIter
202 )
203 {
204 std::string lStr = *lIter;
205 std::string::size_type lPos = lStr.find_first_of("=");
206 std::string lVarName = lStr.substr(0, lPos);
207 std::string lValue;
208 if (lPos != std::string::npos)
209 lValue = lStr.substr(lPos + 1);
210
211 lResult.push_back(std::pair<std::string,std::string>(lVarName, lValue));
212 }
213 return lResult;
214}
21561
=== renamed file 'bin/zorbacmdproperties.h' => 'bin/zorbacmd_props.h'
--- bin/zorbacmdproperties.h 2014-01-31 23:27:47 +0000
+++ bin/zorbacmd_props.h 2014-02-11 00:42:47 +0000
@@ -1,10 +1,10 @@
1/*1/*
2 * Copyright 2006-2008 The FLWOR Foundation.2 * Copyright 2006-2014 The FLWOR Foundation.
3 *3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at6 * You may obtain a copy of the License at
7 * 7 *
8 * http://www.apache.org/licenses/LICENSE-2.08 * http://www.apache.org/licenses/LICENSE-2.0
9 *9 *
10 * Unless required by applicable law or agreed to in writing, software10 * Unless required by applicable law or agreed to in writing, software
@@ -13,114 +13,108 @@
13 * See the License for the specific language governing permissions and13 * See the License for the specific language governing permissions and
14 * limitations under the License.14 * limitations under the License.
15 */15 */
16
16#ifndef ZORBA_CMD_PROPERTIES_H17#ifndef ZORBA_CMD_PROPERTIES_H
17#define ZORBA_CMD_PROPERTIES_H18#define ZORBA_CMD_PROPERTIES_H
1819
20// standard
21#include <string>
22#include <vector>
23#include <utility> /* for pair */
24
25// Zorba
19#include <zorba/config.h>26#include <zorba/config.h>
20#include <zorba/item.h>27
2128///////////////////////////////////////////////////////////////////////////////
22#include "zorbacmdproperties_base.h"29
2330struct external_var {
24class ZorbaCMDProperties : public zorbacmd::ZorbaCMDPropertiesBase 31 std::string var_name;
25{32 std::string var_value;
26public:33 bool inline_file;
27 struct ExternalVariable34
28 {35 external_var() : inline_file( false ) { }
29 std::string var_name;36};
30 std::string var_value;37
31 bool inline_file;38typedef std::vector<external_var> external_vars;
32 };39
3340typedef std::pair<std::string,std::string> serialization_param;
34 typedef std::vector<ExternalVariable> ExternalVars_t;41typedef std::vector<serialization_param> serialization_params;
3542
3643struct sctx_opt {
37 struct StaticContextOption44 std::string clark_qname;
38 {45 std::string value;
39 std::string clark_qname;46};
40 std::string value;47
41 };48typedef std::vector<sctx_opt> sctx_opts;
4249
43 typedef std::vector<StaticContextOption> Options_t;50#ifndef ZORBA_NO_FULL_TEXT
4451struct ft_mapping {
45 struct FullTextMapping52 std::string uri;
46 {53 std::string value;
47 std::string uri;54};
48 std::string value;55
49 };56typedef std::vector<ft_mapping> ft_mappings;
5057#endif /* ZORBA_NO_FULL_TEXT */
51 typedef std::vector<FullTextMapping> FullText_t;58
5259struct ZorbaCmdProperties {
53 typedef std::vector<std::string> QueriesOrFiles_t;60 static ZorbaCmdProperties& instance();
5461
55protected:62 bool as_files_;
56 ExternalVars_t theExternalVars;63 std::string base_uri_;
57 Options_t theStaticContextOptions;64 std::string boundary_space_;
58 FullText_t theStopWordsMapping;65 bool byte_order_mark_;
59 FullText_t theThesaurusMapping;66 std::string classpath_;
6067 bool compile_only_;
61public:68 std::string construction_mode_;
62 ExternalVars_t::const_iterator69 std::string ctx_item_;
63 externalVarsBegin() const { return theExternalVars.begin(); }70#ifdef ZORBA_WITH_DEBUGGER
6471 bool debug_;
65 ExternalVars_t::const_iterator72 std::string debug_host_;
66 externalVarsEnd() const { return theExternalVars.end(); }73 unsigned debug_port_;
6774#endif /* ZORBA_WITH_DEBUGGER */
68 Options_t::const_iterator75 std::string default_collation_;
69 optionsBegin() const { return theStaticContextOptions.begin(); }76 external_vars external_vars_;
7077 bool indent_;
71 Options_t::const_iterator78 bool jsoniq_;
72 optionsEnd() const { return theStaticContextOptions.end(); }79 bool lib_module_;
7380 std::string lib_path_;
74 FullText_t::const_iterator81 bool load_plan_;
75 stopWordsBegin() const { return theStopWordsMapping.begin(); }82 std::string module_path_;
7683 unsigned long multiple_;
77 FullText_t::const_iterator84 bool no_logo_;
78 stopWordsEnd() const { return theStopWordsMapping.end(); }85 bool no_serializer_;
7986 bool omit_xml_declaration_;
80 FullText_t::const_iterator87 unsigned optimization_level_;
81 thesaurusBegin() const { return theThesaurusMapping.begin(); }88 std::string ordering_mode_;
8289#ifdef ZORBA_WITH_FILE_ACCESS
83 FullText_t::const_iterator90 std::string output_file_;
84 thesaurusEnd() const { return theThesaurusMapping.end(); }91#endif /* ZORBA_WITH_FILE_ACCESS */
8592 bool parse_only_;
86 QueriesOrFiles_t::const_iterator93 bool print_errors_as_xml_;
87 queriesOrFilesBegin() const { return theQueriesOrFiles.begin(); }94 bool print_query_;
8895 bool save_plan_;
89 QueriesOrFiles_t::const_iterator96 sctx_opts sctx_opts_;
90 queriesOrFilesEnd() const { return theQueriesOrFiles.end(); }97 bool serialize_html_;
91 98 bool serialize_only_query_;
92 std::vector<std::pair<std::string,std::string> > 99 bool serialize_plan_;
93 getSerializerParameters() const;100 bool serialize_text_;
94101#ifndef ZORBA_NO_FULL_TEXT
95 void102 ft_mappings stop_words_mapping_;
96 getModulePath(std::string&) const;103 ft_mappings thesaurus_mapping_;
97 104#endif /* ZORBA_NO_FULL_TEXT */
98 void105 long timeout_; // unused
99 getURIPath(std::string&) const;106 bool timing_;
100107 bool trailing_nl_;
101 void108 std::string uri_path_;
102 getLibPath(std::string&) const;109
103110 serialization_params serialization_params_;
104 void111 std::vector<std::string> queries_or_files_;
105 getJVMClassPath(std::string&) const;112
106113private:
107 bool isDebug(){ return theDebug; }114 ZorbaCmdProperties();
108115};
109 bool hasNoLogo(){ return theNoLogo; }116
110117///////////////////////////////////////////////////////////////////////////////
111 std::string getDebugHost(){ return theDebugHost; }118
112
113 unsigned int getDebugPort(){ return theDebugPort; }
114
115 std::string check_args ();
116
117 void printHelp(std::ostream& os) const {
118 os << "Zorba NoSQL Query Processor\n";
119 os << "Available options:\n";
120 os << get_help_msg ();
121 }
122
123 bool loadProperties(int argc, char* argv[]);
124};
125#endif /* ZORBA_CMD_PROPERTIES_H */119#endif /* ZORBA_CMD_PROPERTIES_H */
126/* vim:set et sw=2 ts=2: */120/* vim:set et sw=2 ts=2: */
127121
=== removed file 'bin/zorbacmdproperties.txt'
--- bin/zorbacmdproperties.txt 2014-01-31 23:27:47 +0000
+++ bin/zorbacmdproperties.txt 1970-01-01 00:00:00 +0000
@@ -1,40 +0,0 @@
1("as-files,f", "Treat all -q arguments as file paths instead of URIs or inline queries.")
2("base-uri", po::value<std::string>(), "Set the base URI property of the static context.")
3("boundary-space", po::value<std::string>(), "Set the boundary-space policy ('strip' or 'preserve') in the static context.")
4("byte-order-mark", "Set the byte-order-mark for the serializer.")
5("classpath", po::value<std::string>(), "JVM classpath to be used by modules using Java implementations")
6("compile-only", "Only compile (don't execute)")
7("compile-plan,c", "Output the query plan as binary.")
8("construction-mode", po::value<std::string>(), "Set the construction mode ('strip' or 'preserve') in the static context.")
9("context-item", po::value<std::string> (), "Set the context item to the XML document in a given file.")
10("debug,d", "Launch the Zorba debugger server and connect to a DBGP-enabled debugger client.")
11("debug-host,h", po::value<std::string>()->default_value("127.0.0.1"), "The host where the DBGP-enabled debugger client listens for connections. Defaults to: 127.0.0.1")
12("debug-port,p", po::value<unsigned int>()->default_value (28028), "The port on which the DBGP-enabled debugger client listens for connections. Defaults to: 28028")
13("default-collation", po::value<std::string>(), "Add the given collation and set the value of the default collation in the static context to the given collation.")
14("execute-plan", "Take a query plan as binary and execute it. Binary query plans can be generated using the --compile-plan option.")
15("external-variable,e", po::value<std::vector<std::string> >(), "Provide the value for a variable given a file (name=file) or a value (name:=value)")
16("indent,i", "Indent output.")
17("lib-module,l", "Query compiler option to treat the query as a library module. If this is set --compile-only option is also set to true.")
18("lib-path", po::value<std::string>(), "Library path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.")
19("module-path", po::value<std::string>(), "Path (list of directories) to add to both the URI and Library paths.")
20("multiple,m", po::value<unsigned long>()->default_value (1), "Execute the given queries multiple times.")
21("no-logo", "Print no logo when starting.")
22("no-serializer", "Do not serialize (discard) result.")
23("omit-xml-declaration,r", "Omit the XML declaration from the result.")
24("optimization-level", po::value<std::string>()->default_value("O1"), "Optimization level for the query compiler (O0, O1 or O2 - default: O1)")
25("option", po::value<std::vector<std::string> >(), "Set an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://zorba.io/}option=value").
26("ordering-mode", po::value<std::string>(), "Set the ordering mode ('ordered' or 'unordered') in the static context.")
27("output-file,o", po::value<std::string>(), "Write the result to the given file.")
28("parse-only", "Stop after parsing the query.")
29("print-errors-as-xml,x", "Print the errors as XML.")
30("print-query", "Print the queries.")
31("query,q", po::value<std::vector<std::string> >(&theQueriesOrFiles), "Query test or file URI (file://...)")
32("serialization-parameter,z", po::value<std::vector<std::string> >(), "Set serialization parameter in the form of a parameter=value pair (see http://www.w3.org/TR/xslt-xquery-serialization/#serparam, e.g.: -z method=xhtml -z doctype-system=DTD/xhtml1-strict.dtd -z indent=yes).")
33("serialize-html", "Serialize the result as HTML.")
34("serialize-text", "Serialize the result as Text.")
35("stop-words", po::value<std::vector<std::string> >(), "Mapping specifying a stop-words URI to another.")
36("thesaurus", po::value<std::vector<std::string> >(), "Mapping specifying a thesaurus URI to another.")
37("timeout", po::value<long>()->default_value(-1), "Specify a timeout in seconds. After the specified time, the execution of the query will be aborted.")
38("timing,t", "Print timing information. In case of multiple queries the timing information is provided per each query. Both wallclock time and user time (which excludes I/O, network delays and other kernel waits) are shown.")
39("trailing-nl", "Output a trailing newline after the result of the query.")
40("uri-path", po::value<std::string>(), "URI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.")
410
=== removed file 'bin/zorbacmdproperties_base.cpp'
--- bin/zorbacmdproperties_base.cpp 2014-01-31 23:33:01 +0000
+++ bin/zorbacmdproperties_base.cpp 1970-01-01 00:00:00 +0000
@@ -1,374 +0,0 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "zorbacmdproperties_base.h"
18
19namespace zorbacmd {
20
21///////////////////////////////////////////////////////////////////////////////
22
23ZorbaCMDPropertiesBase::ZorbaCMDPropertiesBase() {
24 theAsFiles = true;
25 theByteOrderMark = false;
26 theCompileOnly = false;
27 theDebug = false;
28 theDebugHost = "127.0.0.1";
29 theDebugPort = 28028;
30 theFparm = false;
31 theIndent = false;
32 theLibModule = false;
33 theLoadPlan = false;
34 theMultiple = 1;
35 theNoLogo = false;
36 theNoSerializer = false;
37 theOmitXmlDeclaration = false;
38 theOptimizationLevel = "O1";
39 theParseOnly = false;
40 thePrintErrorsAsXml = false;
41 thePrintQuery = false;
42 theQBeforeF = false;
43 theSavePlan = false;
44 theSerializeHtml = false;
45 theSerializePlan = false;
46 theSerializeText = false;
47 theTimeout = -1;
48 theTiming = false;
49 theTrailingNl = false;
50 theUnknownOption = false;
51}
52
53char const** ZorbaCMDPropertiesBase::get_all_options() const {
54 static const char* result [] = {
55 "--as-files",
56 "--base-uri",
57 "--boundary-space",
58 "--byte-order-mark",
59 "--classpath",
60 "--compile-only",
61 "--compile-plan",
62 "--construction-mode",
63 "--context-item",
64 "--debug",
65 "--debug-host",
66 "--debug-port",
67 "--default-collation",
68 "--disable-http-resolution",
69 "--execute-plan",
70 "--external-variable",
71 "--indent",
72 "--lib-module",
73 "--lib-path",
74 "--module-path",
75 "--multiple",
76 "--no-logo",
77 "--no-serializer",
78 "--omit-xml-declaration",
79 "--optimization-level",
80 "--option",
81 "--ordering-mode",
82#ifdef ZORBA_WITH_FILE_ACCESS
83 "--output-file",
84#endif /* ZORBA_WITH_FILE_ACCESS */
85 "--parse-only",
86 "--print-errors-as-xml",
87 "--print-query",
88 "--query",
89 "--serialization-parameter",
90 "--serialize-html",
91 "--serialize-plan",
92 "--serialize-text",
93 "--stop-words",
94 "--thesaurus",
95 "--timeout",
96 "--timing",
97 "--trailing-nl",
98 "--uri-path",
99 NULL
100 };
101 return result;
102}
103
104#define IS_LONG_OPT(OPT) (strcmp( *argv, (OPT) ) == 0)
105#define IS_SHORT_OPT(OPT) (strncmp( *argv, (OPT), 2 ) == 0)
106#define IS_OPT(LOPT,SOPT) (IS_LONG_OPT(LOPT) || IS_SHORT_OPT(SOPT))
107
108std::string ZorbaCMDPropertiesBase::load_argv(int argc, const char **argv) {
109 if ( !argv )
110 return "";
111
112 std::string result;
113 for ( ++argv; *argv; ++argv ) {
114 if ( IS_OPT( "--help", "-h" ) )
115 return "!HELP";
116 if ( IS_OPT( "--version", "-v" ) )
117 return "!VER";
118
119 if ( IS_OPT( "--as-files", "-f" ) ) {
120 theFparm = true;
121 theAsFiles = true;
122 }
123 else if ( IS_LONG_OPT( "--base-uri" ) ) {
124 int d = 2;
125 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
126 if (!*argv) { result = "No value given for --base-uri option"; break; }
127 init_val(*argv, theBaseUri, d);
128 }
129 else if ( IS_LONG_OPT( "--boundary-space" ) ) {
130 int d = 2;
131 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
132 if (!*argv) { result = "No value given for --boundary-space option"; break; }
133 init_val(*argv, theBoundarySpace, d);
134 }
135 else if ( IS_LONG_OPT( "--byte-order-mark" ) )
136 theByteOrderMark = true;
137 else if ( IS_LONG_OPT( "--classpath" ) ) {
138 int d = 2;
139 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
140 if (!*argv) { result = "No value given for --classpath option"; break; }
141 init_val(*argv, theClasspath, d);
142 }
143 else if ( IS_LONG_OPT( "--compile-only" ) )
144 theCompileOnly = true;
145 else if ( IS_LONG_OPT( "--compile-plan" ) )
146 theSavePlan = true;
147 else if ( IS_LONG_OPT( "--construction-mode" ) ) {
148 int d = 2;
149 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
150 if (!*argv) { result = "No value given for --construction-mode option"; break; }
151 init_val(*argv, theConstructionMode, d);
152 }
153 else if ( IS_LONG_OPT( "--context-item" ) ) {
154 int d = 2;
155 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
156 if (!*argv) { result = "No value given for --context-item option"; break; }
157 init_val(*argv, theContextItem, d);
158 }
159 else if ( IS_OPT( "--debug", "-d" ) )
160 theDebug = true;
161 else if ( IS_OPT( "--debug-host", "-h" ) ) {
162 int d = 2;
163 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
164 if (!*argv) { result = "No value given for --debug-host option"; break; }
165 init_val(*argv, theDebugHost, d);
166 }
167 else if ( IS_OPT( "--debug-port", "-p" ) ) {
168 int d = 2;
169 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
170 if (!*argv) { result = "No value given for --debug-port option"; break; }
171 init_val(*argv, theDebugPort, d);
172 }
173 else if ( IS_LONG_OPT( "--default-collation" ) ) {
174 int d = 2;
175 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
176 if (!*argv) { result = "No value given for --default-collation option"; break; }
177 init_val(*argv, theDefaultCollation, d);
178 }
179 else if ( IS_LONG_OPT( "--execute-plan" ) )
180 theLoadPlan = true;
181 else if ( IS_OPT( "--external-variable", "-e" ) ) {
182 int d = 2;
183 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
184 if (!*argv) { result = "No value given for --external-variable option"; break; }
185 init_val(*argv, theExternalVariable, d);
186 }
187 else if ( IS_OPT( "--indent", "-i" ) )
188 theIndent = true;
189 else if ( IS_OPT( "--lib-module", "-l" ) )
190 theLibModule = true;
191 else if ( IS_LONG_OPT( "--lib-path" ) ) {
192 int d = 2;
193 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
194 if (!*argv) { result = "No value given for --lib-path option"; break; }
195 init_val(*argv, theLibPath, d);
196 }
197 else if ( IS_LONG_OPT( "--module-path" ) ) {
198 int d = 2;
199 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
200 if (!*argv) { result = "No value given for --module-path option"; break; }
201 init_val(*argv, theModulePath, d);
202 }
203 else if ( IS_LONG_OPT( "--no-logo" ) )
204 theNoLogo = true;
205 else if ( IS_LONG_OPT( "--no-serializer" ) )
206 theNoSerializer = true;
207 else if ( IS_OPT( "--multiple", "-m" ) ) {
208 int d = 2;
209 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
210 if (!*argv) { result = "No value given for --multiple option"; break; }
211 init_val(*argv, theMultiple, d);
212 }
213 else if ( IS_OPT( "--omit-xml-declaration", "-r" ) )
214 theOmitXmlDeclaration = true;
215 else if ( IS_LONG_OPT( "--optimization-level" ) ) {
216 int d = 2;
217 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
218 if (!*argv) { result = "No value given for --optimization-level option"; break; }
219 init_val(*argv, theOptimizationLevel, d);
220 }
221 else if ( IS_LONG_OPT( "--option" ) ) {
222 int d = 2;
223 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
224 if (!*argv) { result = "No value given for --option option"; break; }
225 init_val(*argv, theOption, d);
226 }
227 else if ( IS_LONG_OPT( "--ordering-mode" ) ) {
228 int d = 2;
229 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
230 if (!*argv) { result = "No value given for --ordering-mode option"; break; }
231 init_val(*argv, theOrderingMode, d);
232 }
233#ifdef ZORBA_WITH_FILE_ACCESS
234 else if ( IS_OPT( "--output-file", "-o" ) ) {
235 int d = 2;
236 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
237 if (!*argv) { result = "No value given for --output-file option"; break; }
238 init_val(*argv, theOutputFile, d);
239 }
240#endif /* ZORBA_WITH_FILE_ACCESS */
241 else if ( IS_LONG_OPT( "--parse-only" ) )
242 theParseOnly = true;
243 else if ( IS_OPT( "--print-errors-as-xml", "-x" ) )
244 thePrintErrorsAsXml = true;
245 else if ( IS_LONG_OPT( "--print-query" ) )
246 thePrintQuery = true;
247 else if ( IS_OPT( "--query", "-q" ) ) {
248 int d = 2;
249 if(theFparm == false)
250 theAsFiles = false;
251 if(*(argv+1) && !strncmp(*(argv+1), "-f", 2))
252 {
253 theQBeforeF = true; // is it "-q -f <filename>" perhaps?
254 break; // stop functionality here
255 }
256 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
257 if (!*argv) { result = "No value given for --query option"; break; }
258 init_val(*argv, theQueriesOrFiles, d);
259 }
260 else if ( IS_LONG_OPT( "--serialize-html" ) )
261 theSerializeHtml = true;
262 else if ( IS_LONG_OPT( "--serialize-text" ) )
263 theSerializeText = true;
264 else if ( IS_OPT( "--serialization-parameter", "-z" ) ) {
265 int d = 2;
266 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
267 if (!*argv) { result = "No value given for --serialization-parameter option"; break; }
268 init_val(*argv, theSerializationParameter, d);
269 }
270 else if ( IS_LONG_OPT( "--stop-words" ) ) {
271 int d = 2;
272 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
273 if (!*argv) { result = "No value given for --stop-words option"; break; }
274 init_val(*argv, theStopWords, d);
275 }
276 else if ( IS_OPT( "--timing", "-t" ) )
277 theTiming = true;
278 else if ( IS_LONG_OPT( "--timeout" ) ) {
279 int d = 2;
280 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
281 if (!*argv) { result = "No value given for --timeout option"; break; }
282 init_val(*argv, theTimeout, d);
283 }
284 else if ( IS_LONG_OPT( "--trailing-nl" ) )
285 theTrailingNl = true;
286 else if ( IS_LONG_OPT( "--uri-path" ) ) {
287 int d = 2;
288 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
289 if (!*argv) { result = "No value given for --uri-path option"; break; }
290 init_val(*argv, theUriPath, d);
291 }
292 else if ( IS_OPT( "--serialize-plan", "-s" ) )
293 theSerializePlan = true;
294 else if ( IS_LONG_OPT( "--disable-http-resolution" ) ) {
295 init_val("{http://zorba.io/options/features}disable=http-uri-resolution",
296 theOption, 0);
297 }
298 else if ( IS_LONG_OPT( "--thesaurus" ) ) {
299 int d = 2;
300 if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
301 if (!*argv) { result = "No value given for --thesaurus option"; break; }
302 init_val(*argv, theThesaurus, d);
303 }
304
305 else if ( IS_LONG_OPT( "--" ) ) {
306 copy_args (++argv);
307 break;
308 } else if ( (*argv)[0] == '-' ) {
309 result = "unknown command line option "; result += *argv;
310 theUnknownOption = true; break;
311 } else {
312 init_val(*argv, theQueriesOrFiles, 0);
313 copy_args( argv );
314 }
315 } // for
316 return result;
317}
318
319char const* ZorbaCMDPropertiesBase::get_help_msg() const {
320 return
321 "--as-files, -f\nTreat all -q arguments as file paths instead of URIs or inline queries. This option is deprecated and will be defaulted to true in the future, so any entry in the command line is going to be treated as files.\n\n"
322 "--base-uri\nSet the base URI property of the static context.\n\n"
323 "--boundary-space\nSet the boundary-space policy ('strip' or 'preserve') in the static context.\n\n"
324 "--byte-order-mark\nSet the byte-order-mark for the serializer.\n\n"
325 "--classpath\nJVM classpath to be used by modules using Java implementations\n\n"
326 "--compile-only\nOnly compile (don't execute)\n\n"
327 "--compile-plan,\nDo not execute the query; just compile it and save the execution plan in the file specified with the -o option.\n\n"
328 "--construction-mode\nSet the construction mode ('strip' or 'preserve') in the static context.\n\n"
329 "--context-item\nSet the context item to the XML document in a given file.\n\n"
330 "--debug, -d\nLaunch the Zorba debugger server and connect to a DBGP-enabled debugger client.\n\n"
331 "--debug-host, -h\nThe host where the DBGP-enabled debugger client listens for connections. Defaults to: 127.0.0.1\n\n"
332 "--debug-port, -p\nThe port on which the DBGP-enabled debugger client listens for connections. Defaults to: 28028\n\n"
333 "--default-collation\nAdd the given collation and set the value of the default collation in the static context to the given collation.\n\n"
334 "--disable-http-resolution\nDo not use HTTP to resolve URIs\n\n"
335 "--execute-plan\nDo not compile the query; instead load the execution plan from the file specified by the -f -q options (or by any file specified without any other argument), and execute the loaded plan.\n\n"
336 "--external-variable, -e\nProvide the value for a variable given a file (name=file) or a value (name:=value)\n\n"
337 "--indent, -i\nIndent output.\n\n"
338 "--lib-module, -l\nQuery compiler option to treat the query as a library module. If this is set --compile-only option is also set to true.\n\n"
339 "--lib-path\nLibrary path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.\n\n"
340 "--module-path\nPath (list of directories) to add to both the URI and Library paths.\n\n"
341 "--multiple, -m\nExecute the given queries multiple times.\n\n"
342 "--no-logo\nPrint no logo when starting.\n\n"
343 "--no-serializer\nDo not serialize (discard) result.\n\n"
344 "--omit-xml-declaration, -r\nOmit the XML declaration from the result.\n\n"
345 "--optimization-level\nOptimization level for the query compiler (O0, O1 or O2 - default: O1)\n\n"
346 "--option\nSet an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://zorba.io/}option=value\n\n"
347 "--ordering-mode\nSet the ordering mode ('ordered' or 'unordered') in the static context.\n\n"
348 "--output-file, -o\nWrite the result to the given file.\n\n"
349 "--parse-only\nStop after parsing the query.\n\n"
350 "--print-errors-as-xml, -x\nPrint the errors as XML.\n\n"
351 "--print-query\nPrint the queries.\n\n"
352 "--query, -q\nQuery test or file URI (file://...)\n\n"
353 "--serialization-parameter, -z\nSet serialization parameter in the form of a parameter=value pair (see http://www.w3.org/TR/xslt-xquery-serialization/#serparam, e.g.: -z method=xhtml -z doctype-system=DTD/xhtml1-strict.dtd -z indent=yes).\n\n"
354 "--serialize-html\nSerialize the result as HTML.\n\n"
355 "--serialize-plan, -s\nSerialize and then load the query execution plan.\n\n"
356 "--serialize-text\nSerialize the result as Text.\n\n"
357 "--stop-words\nMapping specifying a stop-words URI to another.\n\n"
358 "--thesaurus\nMapping specifying a thesaurus URI to another.\n\n"
359 "--timeout\nSpecify a timeout in seconds. After the specified time, the execution of the query will be aborted.\n\n"
360 "--timing, -t\nPrint timing information. In case of multiple queries the timing information is provided per each query. Both wallclock time and user time (which excludes I/O, network delays and other kernel waits) are shown.\n\n"
361 "--trailing-nl\nOutput a trailing newline after the result of the query.\n\n"
362 "--uri-path\nURI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.\n\n"
363 ;
364}
365
366ZorbaCMDPropertiesBase const* ZorbaCMDPropertiesBase::instance() {
367 static ZorbaCMDPropertiesBase result;
368 return &result;
369}
370
371///////////////////////////////////////////////////////////////////////////////
372
373} // namespace zorbacmd
374/* vim:set et sw=2 ts=2: */
3750
=== removed file 'bin/zorbacmdproperties_base.h'
--- bin/zorbacmdproperties_base.h 2014-01-31 23:27:47 +0000
+++ bin/zorbacmdproperties_base.h 1970-01-01 00:00:00 +0000
@@ -1,142 +0,0 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <string>
18#include <sstream>
19#include <zorba/config.h>
20#include <zorba/properties_base.h>
21#include <cstring>
22
23#ifndef ZORBACMD_ZORBACMDPROPERTIESBASE
24#define ZORBACMD_ZORBACMDPROPERTIESBASE
25namespace zorbacmd {
26
27///////////////////////////////////////////////////////////////////////////////
28
29class ZorbaCMDPropertiesBase : public ::zorba::PropertiesBase {
30protected:
31 bool theTiming;
32#ifdef ZORBA_WITH_FILE_ACCESS
33 std::string theOutputFile;
34#endif /* ZORBA_WITH_FILE_ACCESS */
35 std::vector<std::string> theSerializationParameter;
36 bool theSerializeHtml;
37 bool theSerializeText;
38 bool theIndent;
39 bool thePrintQuery;
40 bool thePrintErrorsAsXml;
41 bool theByteOrderMark;
42 bool theOmitXmlDeclaration;
43 std::string theBaseUri;
44 std::string theBoundarySpace;
45 std::string theDefaultCollation;
46 std::string theConstructionMode;
47 std::string theOrderingMode;
48 unsigned long theMultiple;
49 std::vector<std::string> theQueriesOrFiles;
50 bool theAsFiles;
51 std::vector<std::string> theExternalVariable;
52 std::string theContextItem;
53 std::string theOptimizationLevel;
54 bool theLibModule;
55 bool theParseOnly;
56 bool theCompileOnly;
57 bool theNoSerializer;
58 bool theDebug;
59 std::string theDebugHost;
60 unsigned int theDebugPort;
61 bool theNoLogo;
62 long theTimeout;
63 std::string theUriPath;
64 std::string theLibPath;
65 std::string theModulePath;
66 std::string theClasspath;
67 std::vector<std::string> theOption;
68 bool theTrailingNl;
69 std::vector<std::string> theStopWords;
70 std::vector<std::string> theThesaurus;
71 bool theSerializePlan;
72 bool theSavePlan;
73 bool theLoadPlan;
74 bool theFparm;
75 bool theQBeforeF;
76 bool theUnknownOption;
77
78 // inherited
79 const char** get_all_options() const;
80
81public:
82 ZorbaCMDPropertiesBase();
83
84 bool timing () const { return theTiming; }
85#ifdef ZORBA_WITH_FILE_ACCESS
86 const std::string &outputFile () const { return theOutputFile; }
87#endif /* ZORBA_WITH_FILE_ACCESS */
88 const std::vector<std::string> &serializationParameter () const { return theSerializationParameter; }
89 bool serializeHtml () const { return theSerializeHtml; }
90 bool serializeText () const { return theSerializeText; }
91 bool indent () const { return theIndent; }
92 bool printQuery () const { return thePrintQuery; }
93 bool printErrorsAsXml () const { return thePrintErrorsAsXml; }
94 bool byteOrderMark () const { return theByteOrderMark; }
95 bool omitXmlDeclaration () const { return theOmitXmlDeclaration; }
96 const std::string &baseUri () const { return theBaseUri; }
97 const std::string &boundarySpace () const { return theBoundarySpace; }
98 const std::string &defaultCollation () const { return theDefaultCollation; }
99 const std::string &constructionMode () const { return theConstructionMode; }
100 const std::string &orderingMode () const { return theOrderingMode; }
101 unsigned long multiple () const { return theMultiple; }
102 const std::vector<std::string> &query () const { return theQueriesOrFiles; }
103 bool asFiles () const { return theAsFiles; }
104 const std::vector<std::string> &externalVariable () const { return theExternalVariable; }
105 const std::string &contextItem () const { return theContextItem; }
106 const std::string &optimizationLevel () const { return theOptimizationLevel; }
107 bool libModule () const { return theLibModule; }
108 bool parseOnly () const { return theParseOnly; }
109 bool compileOnly () const { return theCompileOnly; }
110 bool noSerializer () const { return theNoSerializer; }
111 bool debug () const { return theDebug; }
112 const std::string &debugHost () const { return theDebugHost; }
113 unsigned debugPort () const { return theDebugPort; }
114 bool noLogo () const { return theNoLogo; }
115 const long &timeout () const { return theTimeout; }
116 const std::string &uriPath () const { return theUriPath; }
117 const std::string &libPath () const { return theLibPath; }
118 const std::string &modulePath () const { return theModulePath; }
119 const std::string &classpath () const { return theClasspath; }
120 const std::vector<std::string> &option () const { return theOption; }
121 bool trailingNl () const { return theTrailingNl; }
122 const std::vector<std::string> &stopWords () const { return theStopWords; }
123 const std::vector<std::string> &thesaurus () const { return theThesaurus; }
124 bool serializePlan () const { return theSerializePlan; }
125 bool loadPlan () const { return theLoadPlan; }
126 bool savePlan () const { return theSavePlan; }
127 bool qBeforeF () const { return theQBeforeF; }
128 bool unknownOption() const { return theUnknownOption; }
129
130 std::string load_argv(int argc, const char **argv);
131
132 const char* get_help_msg() const;
133
134 static const ZorbaCMDPropertiesBase* instance();
135};
136
137///////////////////////////////////////////////////////////////////////////////
138
139} // namespace zorbacmd
140
141#endif /* ZORBACMD_ZORBACMDPROPERTIESBASE */
142/* vim:set et sw=2 ts=2: */
1430
=== added file 'include/zorba/properties.h'
--- include/zorba/properties.h 1970-01-01 00:00:00 +0000
+++ include/zorba/properties.h 2014-02-11 00:42:47 +0000
@@ -0,0 +1,400 @@
1/*
2 * Copyright 2006-2008 The FLWOR Foundation.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef ZORBA_PROPERTIES_BASE_H
17#define ZORBA_PROPERTIES_BASE_H
18
19// standard
20#include <iostream>
21#include <sstream>
22#include <string>
23#include <vector>
24
25// Zorba
26#include <zorba/config.h>
27#include <zorba/internal/ztd.h>
28#include <zorba/internal/type_traits.h>
29#include <zorba/internal/unique_ptr.h>
30
31namespace zorba {
32
33///////////////////////////////////////////////////////////////////////////////
34
35/**
36 * \brief This class provides access to global properties.
37 *
38 * This class provides access to global properties set for Zorba in environment
39 * and configuration file.
40 */
41class ZORBA_DLL_PUBLIC Properties {
42public:
43 /**
44 * Gets the singleton instance.
45 *
46 * @return Returns said instance.
47 */
48 static Properties& instance();
49
50#ifndef NDEBUG
51 /**
52 * Gets whether abort(3) will be called when a ZorbaException is thrown.
53 * (This is a developer debugging aid.)
54 */
55 bool getAbort() const {
56 return abort_;
57 }
58
59 /**
60 * Sets whether abort(3) will be called when a ZorbaException is thrown.
61 * (This is a developer debugging aid.)
62 *
63 * @param abort If \c true, call abort(3) when a ZorbaException is thrown.
64 */
65 void setAbort( bool abort ) {
66 abort_ = abort;
67 }
68#endif /* NDEBUG */
69
70 /**
71 * Gets the stream used for additional developer debugging output.
72 * (This has nothing to do with the Zorba debugger.)
73 *
74 * @return Returns said stream; default: standard output.
75 */
76 std::ostream& getDebugStream() const {
77 return *debug_stream_.get();
78 }
79
80 /**
81 * Sets the file to use for additional developer debugging output.
82 * (This has nothing to do with the Zorba debugger.)
83 *
84 * @param file The path to the file to use.
85 */
86 void setDebugFile( char const *file );
87
88 /**
89 * Sets the file to use for additional developer debugging output.
90 * (This has nothing to do with the Zorba debugger.)
91 *
92 * @tparam StringType The string type.
93 * @param file The path to the file to use.
94 */
95 template<class StringType>
96 typename std::enable_if<ZORBA_HAS_C_STR(StringType),void>::type
97 setDebugFile( StringType const &file ) {
98 setDebugFile( file.c_str() );
99 }
100
101 /**
102 * Sets the stream to use for additional developer debugging output.
103 * (This has nothing to do with the Zorba debugger.)
104 *
105 * @param stream The stream to use.
106 * @param take_ownership If \c true, \a stream will be deleted when Zorba
107 * shuts down.
108 */
109 void setDebugStream( std::ostream &os, bool take_ownership = false );
110
111 bool getDumpLib() const {
112 return dump_lib_;
113 }
114
115 void setDumpLib( bool b ) {
116 dump_lib_ = b;
117 }
118
119 bool getForceGFLWOR() const {
120 return force_gflwor_;
121 }
122
123 void setForceGFLWOR( bool b ) {
124 force_gflwor_ = b;
125 }
126
127 bool getInferJoins() const {
128 return infer_joins_;
129 }
130
131 void setInferJoins( bool b ) {
132 infer_joins_ = b;
133 }
134
135 bool getInlineUDF() const {
136 return inline_udf_;
137 }
138
139 void setInlineUDF( bool b ) {
140 inline_udf_ = b;
141 }
142
143 std::string const& getClassPath() const {
144 return classpath_;
145 }
146
147 void setClassPath( char const *classpath ) {
148 classpath_ = classpath;
149 }
150
151 template<class StringType>
152 typename std::enable_if<ZORBA_HAS_C_STR(StringType),void>::type
153 setClassPath( StringType const &classpath ) {
154 setClassPath( classpath.c_str() );
155 }
156
157 /**
158 * \brief Get global JVM classpath property.
159 *
160 * Before the JVM is started this will return the classpath set by
161 * command line option, the CLASSPATH environment variable and in Zorba
162 * config file.
163 *
164 * After the JVM is started this will contain in addition the paths to jars
165 * used by modules that make use of the JVM.
166 *
167 * @deprecated Use getClassPath().
168 */
169 void getJVMClassPath( std::string &jvmClasspath ) const {
170 jvmClasspath = getClassPath();
171 }
172
173 /**
174 * \brief Set global JVM classpath property.
175 *
176 * This method should be used to set additional JVM classpath for modules
177 * that make use of JVM. This will overide the classpath set by CLASSPATH
178 * environment variable or Zorba config file.
179 *
180 * Once the JVM is started this method doesn't have any effect.
181 *
182 * @deprecated Use setClassPath().
183 */
184 void setJVMClassPath( std::string const &jvmClasspath ) {
185 setClassPath( jvmClasspath );
186 }
187
188 bool getLoopHoisting() const {
189 return loop_hoisting_;
190 }
191
192 void setLoopHoisting( bool b ) {
193 loop_hoisting_ = b;
194 }
195
196 uint32_t getMaxUDFCallDepth() const {
197 return max_udf_call_depth_;
198 }
199
200 void setMaxUDFCallDepth( uint32_t u ) {
201 max_udf_call_depth_ = u;
202 }
203
204 bool getNoCopyOptim() const {
205 return no_copy_optim_;
206 }
207
208 void setNoCopyOptim( bool b ) {
209 no_copy_optim_ = b;
210 }
211
212 bool getNoTreeIDs() const {
213 return no_tree_ids_;
214 }
215
216 void setNoTreeIDs( bool b ) {
217 no_tree_ids_ = b;
218 }
219
220 unsigned getOptimizationLevel() const {
221 return optimization_level_;
222 }
223
224 void setOptimizationLevel( unsigned optimization_level );
225
226 bool getPrintAST() const {
227 return print_ast_;
228 }
229
230 void setPrintAST( bool b ) {
231 print_ast_ = b;
232 }
233
234 bool getPrintIntermediateOpt() const {
235 return print_intermediate_opt_;
236 }
237
238 void setPrintIntermediateOpt( bool b ) {
239 print_intermediate_opt_ = b;
240 }
241
242 bool getPrintItemFlow() const {
243 return print_item_flow_;
244 }
245
246 void setPrintItemFlow( bool b ) {
247 print_item_flow_ = b ;
248 }
249
250 bool getPrintIteratorTree() const {
251 return print_iterator_locations_;
252 }
253
254 void setPrintIteratorTree( bool b ) {
255 print_iterator_locations_ = b;
256 }
257
258 bool getPrintLocations() const {
259 return print_locations_;
260 }
261
262 void setPrintLocations( bool b ) {
263 print_locations_ = b;
264 }
265
266 bool getPrintOptimized() const {
267 return print_optimized_;
268 }
269
270 void setPrintOptimized( bool b ) {
271 print_optimized_ = b;
272 }
273
274 bool getPrintStaticTypes() const {
275 return print_static_types_;
276 }
277
278 void setPrintStaticTypes( bool b ) {
279 print_static_types_ = b;
280 }
281
282 bool getPrintTranslated() const {
283 return print_translated_;
284 }
285
286 void setPrintTranslated( bool b ) {
287 print_translated_ = b;
288 }
289
290 bool getStableIteratorIDs() const {
291 return stable_iterator_ids_;
292 }
293
294 void setStableIteratorIDs( bool b ) {
295 stable_iterator_ids_ = b;
296 }
297
298 bool getTraceCodegen() const {
299 return trace_codegen_;
300 }
301
302 void setTraceCodegen( bool b ) {
303 trace_codegen_ = b;
304 }
305
306#ifndef ZORBA_NO_FULL_TEXT
307 bool getTraceFulltext() const {
308 return trace_fulltext_;
309 }
310
311 void setTraceFulltext( bool b ) {
312 trace_fulltext_ = b;
313 }
314#endif /* ZORBA_NO_FULL_TEXT */
315
316 bool getTraceParsing() const {
317 return trace_parsing_;
318 }
319
320 void setTraceParsing( bool b ) {
321 trace_parsing_ = b;
322 }
323
324 bool getTraceScanning() const {
325 return trace_scanning_;
326 }
327
328 void setTraceScanning( bool b ) {
329 trace_scanning_ = b;
330 }
331
332 bool getTraceTranslator() const {
333 return trace_translator_;
334 }
335
336 void setTraceTranslator( bool b ) {
337 trace_translator_ = b;
338 }
339
340 bool getUseIndexes() const {
341 return use_indexes_;
342 }
343
344 void setUseIndexes( bool b ) {
345 use_indexes_ = b;
346 }
347
348private:
349 typedef std::unique_ptr<std::ostream> stream_ptr;
350
351 Properties();
352 ~Properties();
353
354#ifndef NDEBUG
355 bool abort_;
356#endif /* NDEBUG */
357 std::string classpath_;
358 stream_ptr debug_stream_;
359 bool owns_debug_stream_;
360 bool dump_lib_;
361 bool force_gflwor_;
362 bool infer_joins_;
363 bool inline_udf_;
364 bool loop_hoisting_;
365 uint32_t max_udf_call_depth_;
366 bool no_copy_optim_;
367 bool no_tree_ids_;
368 unsigned optimization_level_;
369 bool print_ast_;
370 bool print_intermediate_opt_;
371 bool print_item_flow_;
372 bool print_iterator_locations_;
373 bool print_locations_;
374 bool print_optimized_;
375 bool print_static_types_;
376 bool print_translated_;
377 bool stable_iterator_ids_;
378 bool trace_codegen_;
379#ifndef ZORBA_NO_FULL_TEXT
380 bool trace_fulltext_;
381#endif /* ZORBA_NO_FULL_TEXT */
382 bool trace_parsing_;
383 bool trace_scanning_;
384 bool trace_translator_;
385 bool use_indexes_;
386};
387
388// deprecated name
389typedef Properties PropertiesGlobal;
390
391///////////////////////////////////////////////////////////////////////////////
392
393} // namespace zorba
394#endif // ZORBA_PROPERTIES_BASE_H
395/*
396 * Local variables:
397 * mode: c++
398 * End:
399 */
400/* vim:set et sw=2 ts=2: */
0401
=== modified file 'include/zorba/properties_base.h'
--- include/zorba/properties_base.h 2013-02-07 17:24:36 +0000
+++ include/zorba/properties_base.h 2014-02-11 00:42:47 +0000
@@ -1,5 +1,5 @@
1/*1/*
2 * Copyright 2006-2008 The FLWOR Foundation.2 * Copyright 2006-2014 The FLWOR Foundation.
3 * 3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.5 * you may not use this file except in compliance with the License.
@@ -13,136 +13,13 @@
13 * See the License for the specific language governing permissions and13 * See the License for the specific language governing permissions and
14 * limitations under the License.14 * limitations under the License.
15 */15 */
16
16#ifndef ZORBA_PROPERTIES_BASE_H17#ifndef ZORBA_PROPERTIES_BASE_H
17#define ZORBA_PROPERTIES_BASE_H18#define ZORBA_PROPERTIES_BASE_H
1819
19#include <string>20// This is a deprecated header; #include <zorba/properties.h> instead.
20#include <sstream>21
21#include <iostream>22#include <zorba/properties.h>
22#include <vector>23
23#include <cctype>24#endif /* ZORBA_PROPERTIES_BASE_H */
24#include <zorba/config.h>
25
26namespace zorba {
27
28/***************************************************************************//**
29
30********************************************************************************/
31class ZORBA_DLL_PUBLIC PropertiesBase
32{
33protected:
34 std::vector<std::string> thePositionalArgs;
35
36public:
37 virtual ~PropertiesBase() {}
38
39 std::string load_all(
40 const char* cfgFilename,
41 const std::string& env_pfx,
42 int argc,
43 const char **argv)
44 {
45 std::string result;
46
47 if (! (result = load_env(env_pfx)).empty())
48 return result;
49
50 if (! (result = load_file(cfgFilename)).empty())
51 return result;
52
53 return load_argv(argc, argv);
54 }
55
56 std::string load_env(const std::string& env_pfx)
57 {
58 return load_env(env_pfx, get_all_options());
59 }
60
61 std::string load_env(const std::string& env_pfx, const char** options);
62
63 std::string load_file(const char* fname);
64
65 virtual std::string load_argv(int argc, const char **argv) = 0;
66
67 virtual const char** get_all_options() const = 0;
68
69 virtual std::string check_args() { return ""; }
70
71 const std::vector<std::string>& getPositionalArgs() const
72 {
73 return thePositionalArgs;
74 }
75
76 void copy_args (const char** argv)
77 {
78 for (; *argv != NULL; ++argv)
79 {
80 thePositionalArgs.push_back(*argv);
81 }
82 }
83
84 template<class T> void init_val(const char* str, T& val, unsigned delta = 0)
85 {
86 std::istringstream is(str + delta);
87 is >> val;
88 }
89
90};
91
92
93template<> ZORBA_DLL_PUBLIC void PropertiesBase::init_val(
94 const char* str,
95 std::string& val,
96 unsigned delta);
97
98
99template<> ZORBA_DLL_PUBLIC void PropertiesBase::init_val(
100 const char* str,
101 std::vector<std::string>& val,
102 unsigned delta);
103
104/**
105 * \brief This class provides access to global properties.
106 *
107 * This class provides access to global properties set for Zorba in environment
108 * and configuration file.
109 * It is available using Zorba.getProperties() method.
110 * \see { Zorba::getProperties() }
111 */
112class ZORBA_DLL_PUBLIC PropertiesGlobal : public PropertiesBase
113{
114public:
115 virtual ~PropertiesGlobal() {}
116
117 /**
118 * \brief Get global JVM classpath property.
119 *
120 * Before the JVM is started this will return the classpath set by
121 * command line option, the CLASSPATH environment variable and in Zorba
122 * config file.
123 *
124 * After the JVM is started this will contain in addition the paths to jars
125 * used by modules that make use of the JVM.
126 */
127 virtual void getJVMClassPath(std::string & jvmClasspath) {}
128
129 /**
130 * \brief Set global JVM classpath property.
131 *
132 * This method should be used to set additional JVM classpath for modules
133 * that make use of JVM. This will overide the classpath set by CLASSPATH
134 * environment variable or Zorba config file.
135 *
136 * Once the JVM is started this method doesn't have any effect.
137 */
138 virtual void setJVMClassPath(const std::string & jvmClasspath) {}
139};
140
141}
142#endif // ZORBA_PROPERTIES_BASE_H
143/*
144 * Local variables:
145 * mode: c++
146 * End:
147 */
148/* vim:set et sw=2 ts=2: */25/* vim:set et sw=2 ts=2: */
14926
=== modified file 'include/zorba/util/fs_util.h'
--- include/zorba/util/fs_util.h 2013-08-05 22:12:13 +0000
+++ include/zorba/util/fs_util.h 2014-02-11 00:42:47 +0000
@@ -90,6 +90,16 @@
90////////// Directory //////////////////////////////////////////////////////////90////////// Directory //////////////////////////////////////////////////////////
9191
92/**92/**
93 * Gets the directory where per-user configuration files are stored.
94 *
95 * @return Returns said directory.
96 * @throws ZorbaException with a diagnostic of zerr::ZOSE0004_IO_ERROR if it
97 * fails.
98 */
99ZORBA_DLL_PUBLIC
100std::string configdir();
101
102/**
93 * Gets the current directory.103 * Gets the current directory.
94 *104 *
95 * @return Returns said directory.105 * @return Returns said directory.
@@ -269,6 +279,37 @@
269 return path.substr( 0, pos );279 return path.substr( 0, pos );
270}280}
271281
282/**
283 * Gets the extension (the part of the name after the last '.') of the last
284 * path component of the given path name.
285 *
286 * @param path The path to get the extension of.
287 * @return Returns the extension (without the '.') or the empty string if
288 * \a path does not have an extension.
289 */
290inline std::string extension( char const *path ) {
291 char const *const name = base_name( path );
292 char const *const dot = std::strrchr( name, '.' );
293 return dot ? dot + 1 : "";
294}
295
296/**
297 * Gets the extension (the part of the name after the last '.') of the last
298 * path component of the given path name.
299 *
300 * @tparam PathStringType The \a path string type.
301 * @param path The path to get the extension of.
302 * @return Returns the extension (without the '.') or the empty string if
303 * \a path does not have an extension.
304 */
305template<class PathStringType> inline
306typename std::enable_if<ZORBA_IS_STRING(PathStringType),PathStringType>::type
307extension( PathStringType const &path ) {
308 PathStringType const name( base_name( path ) );
309 typename PathStringType::size_type const pos = name.rfind( '.' );
310 return pos != PathStringType::npos ? name.substr( pos + 1 ) : "";
311}
312
272#ifdef ZORBA_WITH_FILE_ACCESS313#ifdef ZORBA_WITH_FILE_ACCESS
273314
274/**315/**
275316
=== modified file 'include/zorba/util/smart_ptr.h'
--- include/zorba/util/smart_ptr.h 2013-06-12 04:55:14 +0000
+++ include/zorba/util/smart_ptr.h 2014-02-11 00:42:47 +0000
@@ -107,6 +107,12 @@
107 return assign (rhs);107 return assign (rhs);
108 }108 }
109109
110 T* release() {
111 T *const temp = p;
112 p = 0;
113 return temp;
114 }
115
110}; // SmartPtr116}; // SmartPtr
111117
112} // namespace zorba118} // namespace zorba
113119
=== modified file 'include/zorba/zorba.h'
--- include/zorba/zorba.h 2013-08-06 08:41:26 +0000
+++ include/zorba/zorba.h 2014-02-11 00:42:47 +0000
@@ -34,7 +34,7 @@
34#include <zorba/xquery.h>34#include <zorba/xquery.h>
35#include <zorba/zorba_string.h>35#include <zorba/zorba_string.h>
36#include <zorba/iterator.h>36#include <zorba/iterator.h>
37#include <zorba/properties_base.h>37#include <zorba/properties.h>
3838
39namespace zorba {39namespace zorba {
4040
@@ -45,7 +45,7 @@
45 * (2) create static contexts,45 * (2) create static contexts,
46 * (3) provides access to the XmlDataManager,46 * (3) provides access to the XmlDataManager,
47 * (4) provides access to the ItemFactory, and47 * (4) provides access to the ItemFactory, and
48 * (5) provides access to the PropertiesGlobal.48 * (5) provides access to the Properties.
49 */49 */
50class ZORBA_DLL_PUBLIC Zorba50class ZORBA_DLL_PUBLIC Zorba
51{51{
@@ -319,9 +319,18 @@
319319
320 /** \brief Gets the singleton instance of Zorba's properties object.320 /** \brief Gets the singleton instance of Zorba's properties object.
321 *321 *
322 * @return zorba::Properties the singleton instance of Zorba's properties object.322 * @return zorba::Properties the singleton instance of Zorba's properties
323 */323 * object.
324 virtual PropertiesGlobal* getPropertiesGlobal() = 0;324 * @deprecated Use Properties::instance() instead.
325 */
326 virtual Properties* getProperties() = 0;
327
328 /**
329 * @deprecated Use Properties::instance() instead.
330 */
331 Properties* getPropertiesGlobal() {
332 return getProperties();
333 }
325334
326}; /* class Zorba */335}; /* class Zorba */
327336
328337
=== modified file 'src/api/CMakeLists.txt'
--- src/api/CMakeLists.txt 2014-01-15 02:07:22 +0000
+++ src/api/CMakeLists.txt 2014-02-11 00:42:47 +0000
@@ -62,6 +62,7 @@
62 store_consts.cpp62 store_consts.cpp
63 streambuf.cpp63 streambuf.cpp
64 mem_streambuf.cpp64 mem_streambuf.cpp
65 properties.cpp
65 transcode_streambuf.cpp66 transcode_streambuf.cpp
66 uuid.cpp67 uuid.cpp
67 module_info_impl.cpp68 module_info_impl.cpp
6869
=== renamed file 'src/system/zorba_properties.cpp' => 'src/api/properties.cpp'
--- src/system/zorba_properties.cpp 2014-01-27 23:42:57 +0000
+++ src/api/properties.cpp 2014-02-11 00:42:47 +0000
@@ -14,377 +14,90 @@
14 * limitations under the License.14 * limitations under the License.
15 */15 */
1616
17#include <cstring>17// standard
1818#include <exception>
19#include "zorba_properties.h"19#include <fstream>
20#include <iostream>
21
22// Zorba
23#include <zorba/config.h>
24#include <zorba/internal/cxx_util.h>
25#include <zorba/properties.h>
26
27#include "util/string_util.h"
28
29using namespace std;
2030
21namespace zorba { 31namespace zorba {
2232
23///////////////////////////////////////////////////////////////////////////////33///////////////////////////////////////////////////////////////////////////////
2434
25ZorbaProperties::ZorbaProperties() {
26 theAbort = false;
27 theCompileOnly = false;
28 theDebug = false;
29 theDumpLib = false;
30 theForceGflwor = false;
31 theInferJoins = true;
32 theInlineUdf = true;
33 theIterPlanTest = false;
34 theJsoniqParser = false;
35 theLibModule = false;
36 theLoopHoisting = true;
37 theMaxUdfCallDepth = 1024;
38 theNoCopyOptim = true;
39 theNoTreeIds = false;
40 theOptimizer = 1;
41 thePrintAst = false;
42 thePrintIntermediateOpt = false;
43 thePrintItemFlow = false;
44 thePrintIteratorTree = false;
45 thePrintLocations = false;
46 thePrintNormalized = false;
47 thePrintOptimized = false;
48 thePrintQuery = false;
49 thePrintStaticTypes = true;
50 thePrintTime = false;
51 thePrintTranslated = false;
52 thePrintXqdoc = false;
53 theReorderGlobals = true;
54 theSerializeOnlyQuery = -1;
55 theSpecializeCmp = true;
56 theSpecializeNum = true;
57 theStableIteratorIds = false;
58 theTestPlanSerialization = false;
59 theTraceCodegen = false;
60 theTraceFulltext = false;
61 theTraceParsing = false;
62 theTraceScanning = false;
63 theTraceTranslator = false;
64 theUseIndexes = true;
65 theUseSerializer = false;
66}
67
68char const** ZorbaProperties::get_all_options() const {
69 static char const *result[] = {
70 "--abort",
71 "--CLASSPATH",
72 "--compile-only",
73 "--debug",
74 "--debug-file",
75 "--dot-plan-file",
76 "--dump-lib",
77 "--external-var",
78 "--force-gflwor",
79 "--infer-joins",
80 "--inline-udf",
81 "--iter-plan-test",
82 "--jsoniq",
83 "--lib-module",
84 "--loop-hoisting",
85 "--max-udf-call-depth",
86 "--no-copy-optim",
87 "--no-tree-ids",
88 "--optimizer",
89 "--plan",
90 "--print-ast",
91 "--print-intermediate-opt",
92 "--print-item-flow",
93 "--print-iterator-tree",
94 "--print-locations",
95 "--print-normalized",
96 "--print-optimized",
97 "--print-query",
98 "--print-static-types",
99 "--print-time",
100 "--print-translated",
101 "--print-xqdoc",
102 "--query",
103 "--reorder-globals",
104 "--result-file",
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches